[英]Update of a Dependency Property when variable or field on which it depends on changes
[英]Update field when property changes
这可能是一个基本问题,因为我是WPF的新手。
我有一个包含文本框和按钮的UserControl(此问题的代码已简化):
<UserControl x:Name="this">
<TextBox Text="{Binding ElementName=this, Path=MyProperty.Value}"/>
<Button x:Name="MyButton" Click="Button_Click"/>
</UserControl>
在后面的代码中,我已将“ MyProperty”注册为DependencyProperty:
public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register("MyProperty", typeof(MyProperty), typeof(MyPropertyNumeric), new UIPropertyMetadata(null));
“ MyProperty”是由我定义的类,实现INotifyPropertyChanged。 “ MyProperty.Value”是对象类型。
单击该按钮时,我在后面的代码中更改了MyProperty.Value。 我想让TextBox自动显示新值。 我希望上面的方法会起作用,因为我已经实现了INotifyPropertyChanged-但这没有。任何人都知道该怎么做吗?
更新属性时,您是否使用属性名称调用OnPropertyChanged事件?
例如,
public class MyProperty : INotifyPropertyChanged {
private string _value;
public string Value { get { return _value; } set { _value = value; OnPropertyChanged("Value"); } }
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name) {
PropertyChangedEventHandler handler = PropertyChanged;
if(handler != null) {
handler(this, new PropertyChangedEventArgs(name));
}
}
}
确保使用您要更新的属性的名称触发PropertyChanged事件,这一点很重要。
尝试添加到Binding Mode =“ OneWay”,我不确定到底该怎么做
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.