【发布时间】:2014-01-09 20:45:44
【问题描述】:
我在搞清楚一些可能很愚蠢的事情时遇到了问题。
我的用户控件的父控件上有这个 xaml:
<Map:LocationInformationControl FarmerID="{Binding SelectedFarmerID}"></Map:LocationInformationControl>
在这个 xaml 所在的控件中,它的视图模型上有 SelectedFarmerID 属性,一切都很好。
我的 LocationInformationControl 是一个自定义控件,我有这个依赖属性:
public static readonly DependencyProperty FarmerIDProperty = DependencyProperty.Register(
"FarmerID",
typeof(int),
typeof(LocationInformationControl),
new FrameworkPropertyMetadata(
0, new PropertyChangedCallback(OnFarmerIDChanged)
));
public int FarmerID
{
get
{
return (int)GetValue(FarmerIDProperty);
}
set
{
SetValue(FarmerIDProperty, value);
}
}
这是我的 On Property Changed 回调
private static void OnFarmerIDChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
}
它开火很好,一切都很好。但是当我像这样将视图模型连接到自定义控件时:
this.DataContext = new LocationInformationViewModel()
属性更改回调将不再触发。我假设这是因为我正在更改控件的数据上下文,所以它不会再找到 FarmerID。但是无论如何我可以像这样设置 ViewModel 并且仍然在同一个控件上具有依赖属性吗?
谢谢, 亚伦
【问题讨论】:
-
不知道为什么,但您的设计似乎不正确。您的控件很好,但您不应该为您的控件创建 ViewModel。控制逻辑本质上是 UI 逻辑,可以使用代码隐藏来运行 UI。您应该允许用户将控件上的 DP 绑定到他们的 VM 的属性,而不是您强制他们使用的 VM。
-
是的,你可能是对的。我只是不会为我的 UserControl 使用视图模型。
-
我在启动 MVVM 时犯了同样的错误。当您尝试使用它时,它会变得更加明显。
-
实际上,现在我想起来了,这让我现在可以使用后面代码中的数据更新视图。
标签: c# wpf mvvm dependency-properties