我有一个名为Data
的班级,其中包含一些公开成员:Name
,Age
,Address
。
我还有一个带有文本框Name
,Age
,Address
的窗口。
Data
对象可以随时更改。
如何将Data
对象绑定到文本框并在对象更改后跟进?
我知道有INotifyPropertyChanged
和“依赖属性”,但我不知道如何使用它们。
修改
public class MyData : INotifyPropertyChanged
{
private string _name;
public string Name
{
get
{
return _name;
}
set
{
if (_name != value)
{
_name = value;
OnPropertyChnged("Name");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
ProppertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(name));
}
}
XAML代码:
xmlns:myApp="clr-namespace:MyApp"
<Window.Resources><myApp:MyData x:key = data/></WindowResources>
<TextBox><TextBox.Text><Binding Source="{StaticResource data}" Path="Name" UpdateSourceTrigger="PropertyChanged"/></TextBox.Text></TextBox>
class OtherClass
{
private MyData data;
//the window that have the binding textbox
private MyWindow window;
public OtherClass()
{
data = new MyData();
data.Name = "new name"
window = new MyWindow();
window.show();
}
}
答案 0 :(得分:4)
来自MSDN的link解释得很清楚。
MSDN链接已停用,添加了类似article的链接。
更改类属性后,属性应该使用属性的名称引发OnPropertyChanged事件,以便View知道刷新它的绑定。
public String Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
this.OnPropertyChanged("Name");
}
}
}
您的文本框应该有一个绑定,例如:
<TextBox Text="{Binding Name}"/>
我有一个ViewModelBase类,这是我为所有要调用的派生模型实现OnPropertyChandedEvent的地方:
/// <summary>
/// An event for when a property has changed.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Virtual method to call the Property Changed method
/// </summary>
/// <param name="propertyName">The name of the property which has changed.</param>
protected virtual void OnPropertyChanged(String propertyName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
答案 1 :(得分:0)
让Data类实现INotifyPropertyChanged。当有人更改数据实例的属性值时,引发事件。然后将适当的DataContext设置为UI,并绑定单个ui元素,例如:
<TextBox Text="{Binding Age}"/>