【发布时间】:2019-10-28 06:55:51
【问题描述】:
所以我想我在 UWP 平台中发现了一个非常有趣的错误。
如果我有一个 textbox 并将其 Text 属性绑定到 int? 依赖属性,那么我会得到以下异常。如果我的使用者将可为空的 int 或不可为空的 int 绑定到控件,这似乎并不重要,会显示相同的错误。看起来它与可以为空的依赖属性直接相关。
Error: Converter failed to convert value of type 'Windows.Foundation.Int32'
to type 'IReference`1<Int32>'; BindingExpression: Path='MyNotNullableInt'
DataItem='ControlSandbox.FooViewModel'; target element is
'ControlSandbox.NumericTextBox' (Name='null');
target property is 'Value' (type 'IReference`1<Int32>').
我什至没有使用转换器,所以我猜这是框架内部发生的事情。下面的示例代码将产生输出
Main.xaml
<Grid Background="White" >
<local:NumericTextBox Value="{Binding MyNotNullableInt, Mode=TwoWay}" />
</Grid>
Main.xaml.cs
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.DataContext = new FooViewModel();
}
}
FooViewModel.cs
public class FooViewModel : INotifyPropertyChanged
{
private int _myNotNullableInt;
public int MyNotNullableInt
{
get { return _myNotNullableInt; }
set { _myNotNullableInt = value; OnPropertyChanged("MyNotNullableInt"); }
}
private int? _myNullableInt;
public int? MyNullableInt
{
get { return _myNullableInt; }
set { _myNullableInt = value; OnPropertyChanged("MyNullableInt"); }
}
public FooViewModel()
{
MyNullableInt = null;
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string prop)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
}
NumericTextBox.xaml
<Grid>
<TextBox Text="{x:Bind Value}" />
</Grid>
NumericTextBox.xaml.cs
public sealed partial class NumericTextBox : UserControl
{
public int? Value
{
get { return (int?)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(int?), typeof(NumericTextBox), new PropertyMetadata(0));
public NumericTextBox()
{
this.InitializeComponent();
}
}
【问题讨论】:
标签: c# data-binding uwp dependency-properties nullable