首页 > 解决方案 > 将自定义对象绑定到自定义用户控件时遇到问题

问题描述

我创建了一个像这样的对象:

 public class Widget : INotifyPropertyChanged {
      int miValue;      

      public int Value {
           get => miValue;
           set {
                miValue = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Value");
           }
      }

      public event PropertyChangedEventHandler PropertyChanged;
 }

现在,我还创建了一个用户控件,其中包含一系列绑定到用户控件属性的文本框:

    public StatBlock ( ) {
        InitializeComponent( );
        DataContext = this;
    }

    public int Points {
        get => ( int )GetValue( PointsProperty );
        set => SetValue( PointsProperty, value );
    }

    public static readonly DependencyProperty PointsProperty = DependencyProperty.Register("Points", typeof(int), typeof(StatBlock), new PropertyMetadata(0));

}

如果我在窗口中使用此 UserControl,我可以为该Points属性分配一个静态值,并且一切正常。但是如果我绑定到一个对象,那么它就不起作用了。为了测试,我做了以下事情:

 <Window.Resources>
    <local:Widget x:Key="test" value="150"/>
</Window.Resources>
<Grid DataContext="{StaticResource test}">
    <local:StatBlock Points="{Binding Value}" Width="65" Height="65"/>
    <TextBox Width="150" Height="35" HorizontalAlignment="Left" Text="{Binding Value}"/>
</Grid>

这只会在我的用户控件中返回一个值 0,即使我们可以看到该值是 150。实际上,标准中的值TextBox是正确的。我错过了什么?谢谢。

标签: c#xaml

解决方案


推荐阅读