简体   繁体   English

属性更改时更新字段

[英]Update field when property changes

This is probably a basic question, since I'm new to WPF.. 这可能是一个基本问题,因为我是WPF的新手。

I have a UserControl that contains a TextBox and a Button (code is simplified for this question) : 我有一个包含文本框和按钮的UserControl(此问题的代码已简化):

<UserControl x:Name="this">
    <TextBox Text="{Binding ElementName=this, Path=MyProperty.Value}"/>
    <Button x:Name="MyButton" Click="Button_Click"/>
</UserControl>

In the code behind I have registered "MyProperty" as DependencyProperty: 在后面的代码中,我已将“ MyProperty”注册为DependencyProperty:

public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register("MyProperty", typeof(MyProperty), typeof(MyPropertyNumeric), new UIPropertyMetadata(null));

A "MyProperty" is a class defined by me, that implements INotifyPropertyChanged. “ MyProperty”是由我定义的类,实现INotifyPropertyChanged。 "MyProperty.Value" is of type object. “ MyProperty.Value”是对象类型。

When the button is clicked, I change MyProperty.Value in the code-behind. 单击该按钮时,我在后面的代码中更改了MyProperty.Value。 I want to have the TextBox to automatically show the new value. 我想让TextBox自动显示新值。 I would expect that the above would work, since I've implemented INotifyPropertyChanged - but it doesn't.. Anyone knows how to do this? 我希望上面的方法会起作用,因为我已经实现了INotifyPropertyChanged-但这没有。任何人都知道该怎么做吗?

Are you calling the OnPropertyChanged event with the name of your property when it is updated? 更新属性时,您是否使用属性名称调用OnPropertyChanged事件?

Eg, 例如,

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));
    }
  }
}

It is important to make sure the PropertyChanged event is fired with the name of the property you want to update. 确保使用您要更新的属性的名称触发PropertyChanged事件,这一点很重要。

尝试添加到Binding Mode =“ OneWay”,我不确定到底该怎么做

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM