c# - 将自定义对象绑定到自定义用户控件时遇到问题
问题描述
我创建了一个像这样的对象:
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
是正确的。我错过了什么?谢谢。
解决方案
推荐阅读
- python - 在pyglet中的偏移处绘制精灵非常慢
- r - 在函数中使用 Min 和 max 函数
- javascript - 我无法使用 access_key 初始化响应式文件管理器
- excel - 为excel VBA中的每一行生成字母数字唯一ID
- asp.net-mvc - 除了电子邮件验证外,MVC4 表单验证不起作用
- ios - 如何在滚动到顶部同时添加侦听器时对从 Firestore 获取的聊天进行分页
- html - 我可以使用相对路径作为基本标签的 href 值吗?
- c# - 无法指示密码字段的 html id 并且无法使用 Win Forms 登录页面
- c++ - c++中的模板通用引用
- hdfs - 通过 geomesa-hbase 摄取命令摄取数据的位置