如何在绑定到uri属性的文本框中处理空字符串和无效的Uri

时间:2014-11-04 15:33:44

标签: c# .net wpf uri

在我的WPF应用程序中,我有一个绑定到Uri属性的文本框。

<TextBox Grid.Column="1" Grid.Row="10" Margin="0,0,4,4" x:Name="txtExportURL" Text="{Binding Path=ProjectExportURL, Mode=TwoWay}"
                             Visibility="{Binding Permissions.CanExportJson, Source={x:Static services:ApplicationUserInfo.Instance}, Converter={StaticResource BoolToVisibilityConverter}}"/>

我尝试对来自文本框的字符串进行验证,如下所示

private Uri _projectExportURL;
 public Uri ProjectExportURL
 {
   get { return _projectExportURL; }
   set
   {
      if(Uri.TryCreate(value, value.AbsoluteUri, out _projectExportURL))
         _projectExportURL = value;
      else
         _projectExportURL = null;
      this.OnPropertyChanged("ProjectExportURL");
    }
}

问题是,当字符串为空或无效的Uri时,TryCreate它不会失败并转到else语句。它失败了,什么也没做。

如何确保将空字符串和无效的Uri设置为null?

1 个答案:

答案 0 :(得分:0)

你的意思是?

if(value == null || string.IsNullOrEmpty(value.ToString()) || !Uri.TryCreate(value, value.AbsoluteUri, out _projectExportURL))
    _projectExportURL = null;
OnPropertyChanged("ProjectExportURL");

不确定什么是空白 Uri。