WPF数据绑定绑定错误通知

Jos*_*ose 4 data-binding wpf mvvm

好的,使用WPF(使用MVVM)并遇到一个问题,想要一些输入.我有一个简单的课程

如下所示(假设我已经实现了IDataErrorInfo):

public class SimpleClassViewModel
{
  DataModel Model {get;set;}
  public int Fee {get { return Model.Fee;} set { Model.Fee = value;}}
}
Run Code Online (Sandbox Code Playgroud)

然后我尝试在xaml中绑定它:

<TextBox Text={Binding Fee, ValidatesOnDataErrors=true}/>
Run Code Online (Sandbox Code Playgroud)

当用户然后清除文本时,会发生数据绑定错误,因为它无法将string.empty转换为int.好吧,费用是必填字段,但因为数据绑定不会转换回来,所以我无法提供错误信息,因为我的课程没有更新.那么我需要做以下事情吗?

public class SimpleClassViewModel
{
  DataModel Model {get;set;}
  int? _Fee;
  public int? Fee 
  {
   get { return _Fee;} 
   set { _Fee = value;if (value.HasValue) { Model.Fee = value;}
  }
}
Run Code Online (Sandbox Code Playgroud)

Dab*_*rnl 5

这可以使用ValueConverter完成:

using System.Windows.Data;

namespace MyNameSpace
{
    class IntToStringConverter:IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return ((int) value).ToString();
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            int result;
            var succes = int.TryParse((string) value,out result);
            return succes ? result : 0;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以在XAML中引用它:

<Window xmlns:local="clr-namespace:MyNameSpace">
   <Window.Resources>
      <local:IntToStringConverter x:Key="IntConverter"/>
   </Window.Resources>
   <TextBox Text={Binding Fee, ValidatesOnDataErrors=true,
            Converter={StaticResource IntConverter}}/>
</Window>
Run Code Online (Sandbox Code Playgroud)