问题描述
为什么我不能绑定到UserControl中的Dependency属性?
我只看到字符串 Test作为默认值,但绑定未在测试应用程序中运行。如果我在文本块对象中的测试应用程序中执行相同的绑定,则它会起作用。因此问题必须出在具有依赖项属性的myItem类中。
Why I can't bind to the Dependency Property in my UserControl?I only see the String "Test" as the default value but the binding does not run in a test application. if i do the same binding in the test application in a textblock object than it works. so the problem must be in the myItem class with the dependencyproperty.
代码:
public partial class myItem : UserControl, INotifyPropertyChanged
{
public static DependencyProperty HeaderProperty =
DependencyProperty.Register("Header", typeof(String), typeof(myItem), new UIPropertyMetadata("Test"));
public myItem()
{
InitializeComponent();
DataContext = this;
}
public String Header
{
get
{
return (String)GetValue(HeaderProperty);
}
set
{
SetValue(HeaderProperty, value);
OnPropertyChanged("Header");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
推荐答案
dependency属性已经可以处理更改通知,因此您无需显式实现INotifyPropertyChanged。
因此,您可以从设置器中删除 OnPropertyChanged( Header);
The dependency property already handles notifying of changes so you don't explicitly have to implement INotifyPropertyChanged.So you can remove the OnPropertyChanged("Header");
from the setter
调用此属性更改的函数的正确方法是在Dependency属性中定义它:
If you wanted to call a function on the change of this property the correct way is to define it in the Dependency property:
public static DependencyProperty HeaderProperty =
DependencyProperty.Register("Header", typeof(String), typeof(myItem), new PropertyMetadata("Test", OnHeaderChanged));
public String Header
{
get
{
return (String)GetValue(HeaderProperty);
}
set
{
SetValue(HeaderProperty, value);
}
}
private void OnHeaderChanged(DependencyObject d, DependencyPropertyChangedEventArgs e){ //do something}
这篇关于WPF:不能绑定到用户控件中的依赖项属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!