WPF 绑定(bind)的源值无效

标签 wpf data-binding binding textbox

我有一个绑定(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/

相关文章:

xaml - Silverlight Xaml 和资源中的 StringFormat

java - JIBX 绑定(bind)和 Google 通讯录(使用Flexible=true)

c# - 为什么datagridview不刷新?

c# - 使用一个 DependencyProperty 在 UserControl 中绑定(bind)具有多个属性的模型

c# - 如何在 DataGridView 中获取选定的数据行?

binding - WEB API 2 自托管主机名问题

.net - WinForms 和 WPF 在同一个项目中?

c# - WPF MVVM中组合框的默认值

wpf - 在WPF文本框中绑定(bind)单元标签

c# - 制作一个适合 Property Change Notification 的类