C# 属性更改时更新字段
这可能是一个基本问题,因为我是WPF的新手 我有一个UserControl,其中包含一个文本框和一个按钮(此问题的代码简化): “MyProperty”是我定义的一个类,它实现INotifyPropertyChanged。“MyProperty.Value”的类型为objectC# 属性更改时更新字段,c#,wpf,xaml,C#,Wpf,Xaml,这可能是一个基本问题,因为我是WPF的新手 我有一个UserControl,其中包含一个文本框和一个按钮(此问题的代码简化): “MyProperty”是我定义的一个类,它实现INotifyPropertyChanged。“MyProperty.Value”的类型为object 单击按钮时,我会更改代码隐藏中的MyProperty.Value。我想让文本框自动显示新值。我希望上面的方法能起作用,因为我已经实现了INotifyPropertyChanged——但它没有。。有人知道怎么做吗?在更新O
单击按钮时,我会更改代码隐藏中的MyProperty.Value。我想让文本框自动显示新值。我希望上面的方法能起作用,因为我已经实现了INotifyPropertyChanged——但它没有。。有人知道怎么做吗?在更新OnPropertyChanged事件时,是否使用您的属性名称调用它 例如
确保使用要更新的属性名称触发PropertyChanged事件非常重要。更新时是否使用属性名称调用OnPropertyChanged事件 例如
确保PropertyChanged事件与您要更新的属性名称一起触发非常重要。尝试添加到绑定模式=“单向”,我不确定定义是什么尝试添加到绑定模式=“单向”,我不确定定义是什么谢谢!我指定了财产的名称(对WPF没有任何意义)而不是“值”,谢谢!我指定了属性的名称(对WPF没有意义)而不是“值”
<UserControl x:Name="this">
<TextBox Text="{Binding ElementName=this, Path=MyProperty.Value}"/>
<Button x:Name="MyButton" Click="Button_Click"/>
</UserControl>
public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register("MyProperty", typeof(MyProperty), typeof(MyPropertyNumeric), new UIPropertyMetadata(null));
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));
}
}
}