gpt4 book ai didi

c# - UWP - 将 TextBox.Text 绑定(bind)到 Nullable

转载 作者:太空狗 更新时间:2023-10-30 00:39:44 26 4
gpt4 key购买 nike

当前无法绑定(bind)到任何 Nullable<T> 是否正确?在通用 XAML 应用程序中?

我在 2013 年找到了这个链接:

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

说明:

Windows 8 应用商店应用不支持绑定(bind)到可为 null 的值。它只是没有进入这个版本。我们已经为 v.Next 找到了有关此行为的错误。

但难道真的还没有修复好吗?

我的绑定(bind):

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

我的属性(property):

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 使用内置转换器,在这种情况下,您可能可以将其与您自己的转换器交换,处理可空值:

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

关于c# - UWP - 将 TextBox.Text 绑定(bind)到 Nullable<int>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33453690/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com