我有两个依赖属性,Value
和MinVal
我希望默认值“Value”取决于“MinVal”
由xaml设置的“MinVal”只有一次
我怎么能这样做?
以下是代码:
public int Value
{
get { return (int)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
// Using a DependencyProperty as the backing store for Value. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(int), typeof(NumericHexUpDown), new UIPropertyMetadata(0, ValueChanged));
private static void ValueChanged(object sender, DependencyPropertyChangedEventArgs e)
{
}
public int MinVal
{
get { return (int)GetValue(MinValProperty); }
set { SetValue(MinValProperty, value); }
}
// Using a DependencyProperty as the backing store for MinVal. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MinValProperty =
DependencyProperty.Register("MinVal", typeof(int), typeof(NumericHexUpDown), new UIPropertyMetadata(0, MinValueChanged));
private static void MinValueChanged(object sender, DependencyPropertyChangedEventArgs e)
{
}
答案 0 :(得分:4)
基本上,您可以为依赖项属性添加强制方法。您的默认值位于元数据中。但是你希望值在加载XAML之后显示它们之前会相互作出反应,并且强制就是这样。
private static void OnMinValChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
((NumericHexUpDown)d).CoerceValue(ValueProperty);
}
private static void OnValueChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
((NumericHexUpDown)d).CoerceValue(MinValProperty);
}
private static object CoerceMinVal(DependencyObject d,
object value)
{
double min = ((NumericHexUpDown)d).MinVal;
return value;
}
private static object CoerceValue(DependencyObject d,
object value)
{
double min = ((NumericHexUpDown)d).MinVal;
double val = (double)value;
if (val < min) return min;
return value;
}
元数据构造函数如下所示
public static readonly DependencyProperty MinValProperty = DependencyProperty.Register(
"MinVal", typeof(int), typeof(NumericHexUpDown),
new FrameworkPropertyMetadata(
0,
new PropertyChangedCallback(OnMinimumChanged),
new CoerceValueCallback(CoerceMinimum)
),
);
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
"Value", typeof(int), typeof(NumericHexUpDown),
new FrameworkPropertyMetadata(
0,
new PropertyChangedCallback(OnValueChanged),
new CoerceValueCallback(CoerceValue)
),
);
参考