[英]Property becoming null C# WPF
I am facing the issue with the property becoming null when I set the data, 我在设置数据时遇到属性变为null的问题,
SelectedItem="{Binding PropertyName,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
public className PropertyName
{
get{return this._PropertyName;}
set{this._PropertyName = value;}
}
The problem is when I assign the data in view model 问题是当我在视图模型中分配数据时
PropertyName = new className ();
The "value"
in the setter is null when I debug and check it 调试并检查设置器中的"value"
为空
The problem is by the Mode=two-way
which states that any changes which are done on UI will be reflected to the property being binded and vice-versa but since you have not added OnPropertyChanged
event of INotifyPropertyChanged
interface to the properties bound to UI , you face the problem. 问题是通过Mode=two-way
,它指出对UI所做的任何更改都将反映到要绑定的属性上,反之亦然,但是由于您尚未将INotifyPropertyChanged
接口的OnPropertyChanged
事件添加到绑定到UI的属性上,你面对问题。 Just add PropertyChanged
to all the properties which are binded to UI, 只需将PropertyChanged
添加到绑定到UI的所有属性,
public className PropertyName
{
get{return this._PropertyName;}
set
{
this._PropertyName = value;
OnPropertyChanged("PropertyName");
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Raises this object's PropertyChanged event.
/// </summary>
/// <param name="propertyName">The property that has a new value.</param>
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);
handler(this, e);
}
}
#endregion
Your class should implement INotifyPropertyChanged
interface 您的类应实现INotifyPropertyChanged
接口
public className PropertyName
{
get { return this._PropertyName; }
set
{
this._PropertyName = value;
if(PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("PropertyName"));
}
}
}
When you changed value of your property in code UI don't know about it and reflect null value back to your property. 当您在代码UI中更改属性的值时,不知道该属性,并将空值反映回您的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.