更新字段时,属性更改 [英] Update field when property changes
问题描述
这可能是一个基本的问题,因为我是新来WPF ..
我有一个包含一个文本框和一个按钮(代码简化了用户控件这个问题):
<用户控件X:名称=这种>
<文本框的文本={绑定的ElementName =此,路径= MyProperty.Value}/>
<按钮X:NAME =用作MyButton点击=Button_Click/>
< /用户控件>
在后面的代码我已经注册myProperty的为DependencyProperty的:
公共静态只读的DependencyProperty MyPropertyProperty = DependencyProperty.Register(myProperty的的typeof(myProperty的)的typeof(MyPropertyNumeric),新UIPropertyMetadata(NULL));
一个myProperty的是我定义的类,即实现INotifyPropertyChanged。 MyProperty.Value是对象类型。
在单击该按钮,我更改代码隐藏MyProperty.Value。我想有文本框自动显示新值。我希望的是,以上会的工作,因为我已经实现INotifyPropertyChanged的 - 但事实并非如此..任何人都知道如何做到这一点。
你叫你的财产,当它被更新的名称OnPropertyChanged事件?
例如,
公共类myProperty的:INotifyPropertyChanged的{
私人字符串_value;
公共字符串值{{返回_value; }集合{_value =值; OnPropertyChanged(值); }}
公共事件PropertyChangedEventHandler的PropertyChanged;
保护无效OnPropertyChanged(字符串名称){
PropertyChangedEventHandler处理器=的PropertyChanged;
如果(处理!= NULL){
处理器(这一点,新PropertyChangedEventArgs(名));
}
}
}
,以确保它是非常重要的PropertyChanged事件被激发与您要更新的属性的名称。
This is probably a basic question, since I'm new to WPF..
I have a UserControl that contains a TextBox and a Button (code is simplified for this question) :
<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:
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.Value" is of type object.
When the button is clicked, I change MyProperty.Value in the code-behind. I want to have the TextBox to automatically show the new value. I would expect that the above would work, since I've implemented INotifyPropertyChanged - but it doesn't.. Anyone knows how to do this?
Are you calling the OnPropertyChanged event with the name of your property when it is updated?
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.
这篇关于更新字段时,属性更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!