Wpf 依赖项属性默认值依赖于另一个依赖项属性
我有两个依赖属性,Wpf 依赖项属性默认值依赖于另一个依赖项属性,wpf,dependency-properties,default-value,Wpf,Dependency Properties,Default Value,我有两个依赖属性,Value和MinVal 我希望“value”的默认值取决于“MinVal”。 xaml只设置了一次“最小值”。 我该怎么做 代码如下: public int Value { get { return (int)GetValue(ValueProperty); } set { SetValue(ValueProperty, value); } } // Using a DependencyProperty as
Value
和MinVal
我希望“value”的默认值取决于“MinVal”。
xaml只设置了一次“最小值”。
我该怎么做 代码如下:
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)
{
}
基本上,将强制方法添加到依赖项属性中。默认值在元数据中。但您希望在加载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;
}
参考资料
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;
}
参考资料