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

本文关键字:lt int gt Nullable TextBox Text 绑定 UWP- | 更新日期: 2023-09-27 18:20:05

当前无法绑定到通用XAML应用程序中的任何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应用商店应用程序不支持绑定到可为null的值。它只是没有进入这个版本。我们已经在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').

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

似乎没有修复。由于XAML使用的是内置转换器,在这种情况下,您可能可以将其与自己的转换器进行交换,处理null值:

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;
    }
}