簡體   English   中英

UWP - 將TextBox.Text綁定到Nullable <int>

[英]UWP - Bind TextBox.Text to Nullable<int>

它是否正確無法綁定到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').

好像它沒有修復。 由於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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM