我有一个类,它可以即时计算它的属性,例如:
class CircleArea
{
public double Radius { get; set; }
public double Area
{
get
{
return Radius * Radius * Math.PI;
}
}
}
我通过执行以下操作使其成为DependencyObject:
class CircleArea:
DependencyObject
{
public static readonly DependencyProperty RadiusProperty =
DependencyProperty.Register("Radius", typeof(double), typeof(CircleArea));
public double Radius
{
get { return (double)GetValue(RadiusProperty); }
set
{
SetValue(RadiusProperty, value);
CoerceValue(AreaProperty);
}
}
internal static readonly DependencyPropertyKey AreaPropertyKey =
DependencyProperty.RegisterReadOnly("Area", typeof(double), typeof(CircleArea), new PropertyMetadata(double.NaN));
public static readonly DependencyProperty AreaProperty = AreaPropertyKey.DependencyProperty;
public double Area
{
get
{
return Radius * Radius * Math.PI;
}
}
}
然后我在XAML中有2个文本框,一个用TwoWay绑定到Radius,另一个用OneWay绑定到Area.
如何对Radius的文本框进行编辑更新区域的文本框?
最佳答案 有几种方法可以做到这一点.
>为简单起见,您可以实现INotifyPropertyChanged,为Area使用常规属性,然后在RadiusProperty的OnDependencyPropertyChanged中触发事件.
>为了更复杂,只要Radius发生变化,就可以私下使用密钥设置AreaProperty.你的财产看起来像这样.
public static readonly DependencyProperty RadiusProperty =
DependencyProperty.Register(
"Radius",
typeof(double),
typeof(CircleArea),
new FrameworkPropertyMetadata(0.0, OnRadiusChanged))
private static void OnRadiusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Area = Radius * Radius * Math.PI;
}
private static readonly DependencyPropertyKey AreaKey=
DependencyProperty.RegisterReadOnly("Area", typeof(double)...
public static readonly DependencyProperty AreaProperty = AreaKey.DependencyProperty;
public Double Area
{
get
{
return (Double)GetValue(AreaProperty);
}
private set
{
SetValue(AreaKey, value);
}
}
您仍然可以设置单向绑定到区域.