我有一个绑定(bind)到整数属性的TextBox
。
我该怎么做才能在 TextBox
中没有任何有效文本时将该属性设置为 0。
我真的认为这可以扩展,以便如果绑定(bind)失败,那么我们将源设置为默认(T)。
我需要朝正确的方向插入。
TargetNullValue
与我正在寻找的相反(我认为),它在源为空时设置 TextBox
文本。我希望当 TextBox
文本是无效的绑定(bind)值时将源设置为其默认值。
最佳答案
将如下所示的 Converter
应用到您的绑定(bind)中应该可以解决问题:
public class TextConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
int actual = (int)value;
return actual.ToString();
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
string actual = (string)value;
int theValue = 0;
int.TryParse(actual, out theValue);
return theValue;
}
}
您的 TextBox
绑定(bind)看起来像这样:
<TextBox Text="{Binding ... Converter={StaticResource convert}}"></TextBox>
将转换器定义为您的 Window/Control/... 的资源
关于WPF 绑定(bind)的源值无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2292541/