我的MainPage中有一个Textblock项,它绑定myClass对象的值。我还有一个按钮,可以更改此对象的属性值。虽然在单击按钮并实现INotifyPropertyChanged
接口时更新值,但表示的值不会更改。这是我的代码:
public class myClass : INotifyPropertyChanged
{
//Fields declaration <---------------------------------------------------->
private int lifetime;
private DateTime startingDate;
private string brand;
private double power;
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
public int Lifetime {
get
{
return lifetime;
}
set
{
if (value != lifetime)
{
lifetime = value;
NotifyPropertyChanged("Lifetime");
}
}
}
public DateTime StartingDate {
get
{
return startingDate;
}
set
{
if (value != startingDate)
{
startingDate = value;
NotifyPropertyChanged("StartingDate");
}
}
}
public string Brand
{
get
{
return brand;
}
set
{
if (value != brand)
{
brand = value;
NotifyPropertyChanged("Brand");
}
}
}
public double Power
{
get
{
return power;
}
set
{
if (value != power)
{
power = value;
NotifyPropertyChanged("Power");
}
}
}
public int DaysRemaining
{
get
{
return Lifetime - (DateTime.Now - StartingDate).Days;
}
}
//Functions declaration <------------------------------------------------>
public ContactLens()
{
StartingDate = new DateTime();
}
}
按钮功能会更改startingDate
值,因此也应更改DaysRemaining
值。
private void leftButtonChange_Click(object sender, RoutedEventArgs e)
{
Model.Left.StartingDate = DateTime.Now;
}
private void rightChangeButton_Click(object sender, RoutedEventArgs e)
{
Model.Right.StartingDate = DateTime.Now;
}
修改
我创建了一个更新日期并再次计算DaysRemaining
的方法,但是尽管textBlock绑定到StartingDate
更改值,但DaysRemaining
值要求重新启动应用以进行更改:
private void leftButtonChange_Click(object sender,RoutedEventArgs e)
{
Model.Left.Replace();
}
private void rightChangeButton_Click(object sender, RoutedEventArgs e)
{
Model.Right.Replace();
}
主要的功能:
public void Replace()
{
MessageBox.Show("" + daysRemaining);
StartingDate = DateTime.Now;
UpdateDaysRemaining();
MessageBox.Show("" + daysRemaining);
}
答案 0 :(得分:0)
您的StartingDate属性会触发更改通知,以便直接绑定到它的任何内容都会更新,但DaysRemaining属性不会触发更改通知。 DaysRemaining需要触发更改通知,让绑定到它的对象知道需要更新。
DaysRemaining有点奇怪,因为它是从其他三个值计算而不是明确设置。
将DaysRemaining与BeginDate和Lifetime联系起来非常简单:它们在同一个类中密切相关,而StartingDate和Lifetime仅根据其setter进行更改。您可以让StartingDate和Lifetime在DaysRemaining更改时触发更改通知,StartingDate和Lifetime可以设置DaysRemaining,以便DaysRemaining可以触发自己的通知,或者DaysRemaining可以监听StartingDate和Lifetime的更改通知(这最后一个可能是矫枉过正的。)
更棘手的部分是DaysRemaining将随DateTime.Now而改变。 DateTime.Now是类的外部,并且将比您关心的更频繁地更改。你只关心(DateTime.Now - StartingDate).Days改变,并且这是可预测的。而不是绑定到DateTime.Now我将计算天数何时更改并设置计时器以更新DaysRemaining。