它可能仍然很冗长,但实际上您可以使用 DependencyProperties 执行此操作:
将“OnChanged”回调附加到更新 DP 的DPRaiseTime
和DP,并使 TotalTime 只读(不同的 DP 注册语法,并且只有一个私有设置器):FallTime
TotalTime
public TimeSpan RaiseTime
{
get { return (TimeSpan)GetValue(RaiseTimeProperty); }
set { SetValue(RaiseTimeProperty, value); }
}
public static readonly DependencyProperty RaiseTimeProperty =
DependencyProperty.Register("RaiseTime", typeof(TimeSpan), typeof(MainWindow),
new PropertyMetadata(TimeSpan.Zero, OnRaiseTimeChanged));
private static void OnRaiseTimeChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var owner = sender as MainWindow;
owner.TotalTime = owner.RaiseTime + owner.FallTime;
}
public TimeSpan FallTime
{
get { return (TimeSpan)GetValue(FallTimeProperty); }
set { SetValue(FallTimeProperty, value); }
}
public static readonly DependencyProperty FallTimeProperty =
DependencyProperty.Register("FallTime", typeof(TimeSpan), typeof(MainWindow),
new PropertyMetadata(TimeSpan.Zero, OnFallTimeChanged));
private static void OnFallTimeChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var owner = sender as MainWindow;
owner.TotalTime = owner.RaiseTime + owner.FallTime;
}
/// <summary>
/// Read-only DP:
/// http://msdn.microsoft.com/en-us/library/ms754044.aspx
/// http://www.wpftutorial.net/dependencyproperties.html
/// </summary>
public TimeSpan TotalTime
{
get { return (TimeSpan)GetValue(TotalTimeProperty); }
private set { SetValue(TotalTimePropertyKey, value); }
}
public static readonly DependencyPropertyKey TotalTimePropertyKey =
DependencyProperty.RegisterReadOnly("TotalTime", typeof(TimeSpan), typeof(MainWindow),
new PropertyMetadata(TimeSpan.Zero));
public static readonly DependencyProperty TotalTimeProperty = TotalTimePropertyKey.DependencyProperty;
默认值需要相加(这里:0 + 0 = 0)。之后,OnRaiseTimeChanged
会OnFallTimeChanged
不断TotalTime
更新。