为什么我无法绑定到UserControl中的Dependency属性? 我只看到字符串“Test”作为默认值,但绑定不在测试应用程序中运行。如果我在文本块对象中的测试应用程序中执行相同的绑定而不是它的工作。所以问题必须在带有dependencyproperty的myItem类中。
代码:
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));
}
}
}
答案 0 :(得分:0)
依赖项属性已经处理通知更改,因此您不必显式实现INotifyPropertyChanged。
因此,您可以从设置器中删除OnPropertyChanged("Header");
如果要在更改此属性时调用函数,正确的方法是在Dependency属性中定义它:
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}