【发布时间】:2016-05-30 08:40:11
【问题描述】:
我有一个带有矩形的视图,并且根据一个布尔变量,我想将填充设置为特定的画笔。为此,我向 ViewModel 添加了一个 DependencyProperty。
public static readonly DependencyProperty FalseColorProperty = DependencyProperty.Register(
"FalseColor",
typeof(Brush),
typeof(BooleanRectangleView),
new FrameworkPropertyMetadata(Application.Current.FindResource("LightGreyBrush"), FrameworkPropertyMetadataOptions.AffectsRender));
public Brush FalseColor
{
get { return (Brush)GetValue(FalseColorProperty); }
set { SetValue(FalseColorProperty, value); }
}
在视图中,我使用以下触发器为矩形添加了一个样式
<DataTrigger Binding="{Binding DataContext.Model.Variable, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="false">
<Setter Property="Fill" Value="{Binding DataContext.FalseColor, RelativeSource={RelativeSource AncestorType=UserControl}}" />
</DataTrigger>
由于我在 ViewModel 中有 DependencyProperty,我不知道在创建 UserControl 时如何设置它。例如,以下不起作用
<BooleanRectangleView FalseColor="..."/>
另外,当我运行程序时,我在 ViewModel 的构造函数中得到一个异常:
默认类型与属性
FalseColor的类型不匹配(翻译自德语)
编辑:
当我将 FindResource 转换为 Brush 时,我得到一个新异常:
属性
FalseColor的默认值不能绑定到特定线程
我猜这与不一定从调度程序线程调用 FindResource 有关?
【问题讨论】:
-
如果你在 ViewModel 类中放置一个 DP,这个类将是一个 DependencyObject。你不想要那个。您只需要一个引发 INotifyPropertyChanged 的属性。你可能写错了,它可能在你的 View 类中。关于您的问题:您需要在 Style 和 DataTrigger 中设置 FalseColor。关于您的默认值问题:您需要将 FindResource 转换为 Brush
-
@nkoniishvt:你能解释一下为什么我不希望 ViewModel 成为 DependencyObject 吗?
-
拥有依赖属性的原因(通常)都不适用于视图模型属性。您不希望视图模型属性成为绑定的目标,或者在样式设置器中设置,或者被动画等等。
-
ViewModel 层应该为 View 提供数据显示,并允许 View 层更新 Model 层中的数据。作为一个 DependencyObject 意味着它是一个视图元素并且有很多对 ViewModel 层没有用的开销(例如,Dispatcher、属性动画,它对 ViewModel 类没有用)
-
@nkoniishvt:好的,我明白了,但是我有两个数据上下文的问题。一个用于 ViewModel,一个用于 DependencyProperty。它是如何工作的?
标签: c# wpf xaml mvvm dependency-properties