UWP - 将TextBox.Text绑定到Nullable <int>

时间:2015-10-31 16:10:54

标签: c# data-binding uwp

目前无法绑定到Universal XAML Apps中的任何Nullable<T>,这是否正确?

我从2013年发现了这个链接:

https://social.msdn.microsoft.com/Forums/en-US/befb9603-b8d6-468d-ad36-ef82a9e29749/textbox-text-binding-on-nullable-types?forum=winappswithcsharp

说明:

Windows 8商店应用程序不支持绑定到可空值。它只是没有进入这个版本。对于v.Next,我们已经有了这种行为的错误。

但真的可以解决这个问题吗?

我的约束力:

<TextBox Text="{Binding Serves, Mode=TwoWay}" Header="Serves"/>

我的财产:

public int? Serves
{
    get { return _serves; ; }
    set
    {
        _serves = value;
        OnPropertyChanged();
    }
}

我在输出中得到的错误:

Error: Cannot save value from target back to source. 
BindingExpression: 
    Path='Serves' 
    DataItem='MyAssembly.MyNamespace.RecipeViewModel, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'; target element is 'Windows.UI.Xaml.Controls.TextBox' (Name='null'); target property is 'Text' (type 'String').

1 个答案:

答案 0 :(得分:6)

似乎没有修复。由于XAML使用的是内置转换器,在这种情况下,你可以将它与你自己的交换,处理nullables:

XAML:

<StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <StackPanel.Resources>
        <local:NullConverter x:Key="NullableIntConverter"/>
    </StackPanel.Resources>
    <TextBox Text="{Binding Serves, Mode=TwoWay, Converter={StaticResource NullableIntConverter}}" Header="Serves"/>
</StackPanel>

代码背后:

public class NullConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    { return value; }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        int temp;
        if (string.IsNullOrEmpty((string)value) || !int.TryParse((string)value, out temp)) return null;
        else return temp;
    }
}

public sealed partial class MainPage : Page, INotifyPropertyChanged
{
    private int? _serves;

    public event PropertyChangedEventHandler PropertyChanged;
    public void RaiseProperty(string name) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));

    public int? Serves
    {
        get { return _serves; }
        set { _serves = value; RaiseProperty("Serves"); }
    }

    public MainPage()
    {
        this.InitializeComponent();
        DataContext = this;
    }
}