绑定到Nullable Int32时,绑定表达式错误

时间:2019-06-13 16:08:49

标签: c# data-binding uwp dependency-properties nullable

所以我认为我在UWP平台中发现了一个非常有趣的错误。

如果我有一个textbox并将其Text属性绑定到一个int?依赖属性,那么将得到以下异常。如果我的使用者将nullable int或nonnullable 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();
        }
    }

1 个答案:

答案 0 :(得分:1)

因此,我不确定为什么在研究错误的最初几个小时都没有回到此页面,但是,至少现在这篇文章会记录下来,以供将来使用。

我正在研究绑定到可为空的依赖项属性,并且遇到this article

  

事实证明,大部分.NET基本类型是   转换为等效的Windows运行时类型。 IReference碰巧   是Windows运行时等效于.NET的Nullable。

它说,您需要将依赖项属性的属性类型typeof从可空类型更改为object

我已经确认可以。

public static readonly DependencyProperty ValueProperty =
            DependencyProperty.Register("Value", typeof(object), typeof(NumericTextBox), new PropertyMetadata(0));
相关问题