C# 绑定到可为null的Int32时出现绑定表达式错误
所以我想我在UWP平台上发现了一个非常有趣的bug 如果我有一个C# 绑定到可为null的Int32时出现绑定表达式错误,c#,data-binding,uwp,dependency-properties,nullable,C#,Data Binding,Uwp,Dependency Properties,Nullable,所以我想我在UWP平台上发现了一个非常有趣的bug 如果我有一个textbox,并且我将它的Text属性绑定到int?依赖属性,那么我会得到以下异常。如果我的使用者将一个可为null的int或不可为null的int绑定到控件,则似乎无关紧要,显示相同的错误。它看起来与可为null的依赖项属性直接相关 Error: Converter failed to convert value of type 'Windows.Foundation.Int32' to type 'IReference`1&
textbox
,并且我将它的Text
属性绑定到int?
依赖属性,那么我会得到以下异常。如果我的使用者将一个可为null的int或不可为null的int绑定到控件,则似乎无关紧要,显示相同的错误。它看起来与可为null的依赖项属性直接相关
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>').
FooViewModel.cs
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.DataContext = new FooViewModel();
}
}
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));
}
}
}
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();
}
}
NumericTextBox.xaml
<Grid Background="White" >
<local:NumericTextBox Value="{Binding MyNotNullableInt, Mode=TwoWay}" />
</Grid>
<Grid>
<TextBox Text="{x:Bind Value}" />
</Grid>
因此,我不知道为什么在我们研究错误的最初几个小时,这一页没有回来,但是,至少这篇文章现在将记录这一点,以备将来使用 我在研究绑定到可为空的依赖项属性时,遇到了 事实证明,大多数.NET基元类型都是 已转换为等效的Windows运行时类型。i引用发生在 Windows运行时等效于.NET中的Nullable 它说,您需要将dependency属性上的属性类型
typeof
从可为空的类型更改为object
我已经确认这是有效的
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(object), typeof(NumericTextBox), new PropertyMetadata(0));