Kyl*_*yle 3 .net data-binding wpf properties
我对数据绑定有点新鲜,显然不太了解它.我正在尝试将一个简单的.net属性绑定到一个标签,并在更改属性时更新该标签.它不起作用,我不确定问题出在哪里.
这是我的XAML
<Label Content="{Binding Path=Name, UpdateSourceTrigger=PropertyChanged}"></Label>
<Button Name="bChangeProperty" Click="bChangeProperty_Click">Change Property</Button>
Run Code Online (Sandbox Code Playgroud)
这是我的UserControl cs文件
public partial class MyUserControl : UserControl, INotifyPropertyChanged
{
private MyObjectClass _myObject;
public MyObjectClass MyProperty
{
get { return _myObject;}
set
{
if (_myObject != value)
{
_myObject = value;
OnPropertyChanged("MyProperty");
}
}
}
public MyUserControl(MyObjectClass obj)
{
if (obj == null)
{
obj = new MyObjectClass();
obj.Name = "Frank";
}
MyProperty= obj;
base.DataContext = MyProperty;
}
//INotifyPropertyChanged stuff
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
//PropertyChanged is always null, don't really understand this part
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
private void bChangeProperty_Click(object sender, RoutedEventArgs e)
{
//Create a new object, and set it to the MyProperty Property - which I thought
//would update the label, but it doesn't
MyObjectClass newObject = new MyObjectClass();
newObject.Name = "Bob";
MyProperty= newObject;
}
Run Code Online (Sandbox Code Playgroud)
这是MyObjectClass
public class MyObjectClass
{
public string Name {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
初始绑定有效,它会将Label设置为"Frank",但是当我单击按钮并更改对象时,标签将不会更新.这只是我喜欢做的事情的一个例子.
我必须将PropertyChanged设置为某个地方吗?我有点想到这就是XAML想要做的事情,但看看它总是如何无效,显然它不是.
您需要实现INotifyPropertyChanged上MyObjectClass和火灾PropertyChanged之后MyObjectClass.Name发生了变化.
public class MyObjectClass : INotifyPropertyChanged
{
private string name;
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
OnPropertyChanged("Name");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
Run Code Online (Sandbox Code Playgroud)