UWP - Bind TextBox.Text to Nullable <int>

Is it right that it’s currently impossible to bind to anyone Nullable<T>in Universal XAML Apps?

I have found this link since 2013:

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

The statement that:

Binding to values ​​with a null value is not supported in Windows 8 Store applications. He just did not get into this release. We already have errors in this behavior for v.Next.

But can it be that this has not yet been fixed?

My binding:

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

My property:

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

And the error I get in my output:

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').
+4
source share
1 answer

, . 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;
    }
}
+6

Source: https://habr.com/ru/post/1613978/


All Articles