WPF绑定与int类型的属性无法正常工作

akj*_*shi 9 c# data-binding silverlight wpf xaml

int在我的视图模型中有一个类型的属性,它绑定到a TextBox.一切正常,TwoWay绑定工作正常,除了一个案例 -

如果我清除了值TextBox,则不会调用属性setter,虽然清除了值TextBox,但属性仍保留先前的值.

有没有人遇到类似的问题?这有什么解决方法吗?

这是物业 -

public int MaxOccurrences
{
    get
    {
        return this.maxOccurrences;
    }
    set
    {
        if (this.maxOccurrences != value)
        {
            this.maxOccurrences = value;
            base.RaisePropertyChanged("MaxOccurrences");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我如何绑定xaml中的属性 -

<TextBox Text="{Binding Path=MaxOccurrences, Mode=TwoWay, 
    NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}" 
    HorizontalAlignment="Center" Width="30" Margin="0,0,5,0"/>
Run Code Online (Sandbox Code Playgroud)

WPF*_*ser 25

我有类似的问题.

您只需将代码更新为:

<TextBox Text="{Binding Path=MaxOccurrences, Mode=TwoWay, TargetNullValue={x:Static sys:String.Empty},
NotifyOnSourceUpdated=True,  UpdateSourceTrigger=PropertyChanged}"  
HorizontalAlignment="Center" Width="30" Margin="0,0,5,0"/> 
Run Code Online (Sandbox Code Playgroud)

  • `的xmlns:SYS = "CLR-命名空间:系统;装配= mscorlib程序"` (10认同)
  • 对于 .net 3.5 或更高版本,请尝试 `TargetNullValue=''` (3认同)

Sim*_*ens 6

这部分是一个猜测(我现在没有得到VS方便尝试),但我认为这是因为一个清除的文本框是一个空string(""),它不能隐式转换为int.您可能应该实现类型转换器来为您提供转换.(你可能想要做一些像转换""到0)


Moh*_*dil 6

如果您不想使用a Nullable integer,可以使用converter将空转换string为0,请参阅下面的代码:

public class EmptyStringToZeroConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value == null || string.IsNullOrEmpty(value.ToString())
            ? 0
            : value;
    }

    #endregion
}
Run Code Online (Sandbox Code Playgroud)