我在 WPF 应用程序的 ViewModel 中有这个简单的示例:
class VM_DiskPartition : DependencyObject
{
// (...) Other properties
public bool IsLowOnSpace
{
get { return (bool)GetValue(IsLowOnSpaceProperty); }
set { SetValue(IsLowOnSpaceProperty, value); }
}
public static readonly DependencyProperty IsLowOnSpaceProperty = DependencyProperty.Register("IsLowOnSpace", typeof(bool), typeof(VM_DiskPartition), new PropertyMetadata(false, OnLowOnSpaceChanged));
private static void OnLowOnSpaceChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
{
((VM_DiskPartition)d).CoerceValue(BgColorProperty);
}
public Brush BgColor
{
get { return (Brush)GetValue(BgColorProperty); }
set { SetValue(BgColorProperty, value); }
}
public static readonly DependencyProperty BgColorProperty = DependencyProperty.Register("BgColor", typeof(Brush), typeof(VM_DiskPartition), new PropertyMetadata(Brushes.Red, null, Coerce_BgColor));
private static object Coerce_BgColor(DependencyObject d, object baseValue)
{
return UIUtils.GetBgColor(((VM_DiskPartition)d).IsLowOnSpace);
}
}
我希望 BgColor 属性的默认值由其强制函数自动设置。
有没有更优雅的方法来实现这一点,而不是调用
CoerceValue(BgColorProperty)
从构造函数?原因是我将来可能会有很多这样的属性,并且在构造函数中使用大量 CoerceValue() 调用看起来不太干净。
也许在这种情况下使用转换器会更好?我试图不使用它们,而是创建新的 ViewModel 属性。
最佳答案
您似乎有些困惑... DependencyObject
和 DependencyProperty
类是 UI 类。它们不属于 View 模型。在 View 模型中,我们使用普通的 CLR 属性和 INotifyPropertyChanged
处理属性更改通知的接口(interface)。因此,根本不需要在 View 模型中使用它们。
如果要在 View 模型中设置默认值,只需执行以下操作:
private int number = 5; // <-- default value
public int Number
{
get { return number; }
set { number = value; NotifyPropertyChanged("Number"); }
}
如果你想在 View 模型中强制属性值,你只需这样做:
public int Number
{
get { return number; }
set { number = Math.Max(0, value); NotifyPropertyChanged("Number"); }
}
更新>>>
再次查看您的代码,我发现它根本不应该在 View 模型中。看起来它应该在一些
UserControl
后面的代码中.我们将数据放在 View 模型中,而不是像 Brush
这样的 UI 元素es。如果您想为 DependencyProperty
设置默认值,正确的做法是您向我们展示的方式:public static readonly DependencyProperty BgColorProperty =
DependencyProperty.Register("BgColor", typeof(Brush), typeof(VM_DiskPartition),
new PropertyMetadata(Brushes.Red/* <-- default value */, null, Coerce_BgColor));
属性强制是为了确保一个值保持在一定的范围内,就像我上面给出的例子一样,确保这个值永远不会是负数。
关于c# - DependencyProperty 默认值取决于强制逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21915946/