Xaml 当其他内容发生更改时,非DP ViewModel需要属性集

Xaml 当其他内容发生更改时,非DP ViewModel需要属性集,xaml,mvvm,Xaml,Mvvm,我有一个UserControl,它显示与系统中活动人员相关的数据。此UC有一个DependencyProperty“Person”,由“拥有”UC实例的人设置 要显示与UC中的人员关联的数据,我有一个ViewModel。ViewModel需要知道UC的person中当前设置了哪个person 最初我试过这样做: ...snip... <UserControl.Resources> <ResourceDictionary> ...snip...

我有一个UserControl,它显示与系统中活动人员相关的数据。此UC有一个DependencyProperty“Person”,由“拥有”UC实例的人设置

要显示与UC中的人员关联的数据,我有一个ViewModel。ViewModel需要知道UC的person中当前设置了哪个person

最初我试过这样做:

...snip...
<UserControl.Resources>
    <ResourceDictionary>
        ...snip...

        <vms:TheViewModel x:Key="ViewModel" Person={Binding somebinding to the UC's Person}/>
    </ResourceDictionary>
</UserControl.Resources>
...snip...
…剪断。。。
剪

当依赖项属性更改时,获取视图模型资源并在视图模型上设置属性

public static readonly DependencyProperty PersonProperty = 
    DependencyProperty.Register(
    "Person", typeof(PersonObject),
    typeof(MyUserControl), new FrameworkPropertyMetadata(null,
      FrameworkPropertyMetadataOptions.AffectsRender, 
      new PropertyChangedCallback(OnPersonChanged) )
    );

private static void OnPersonChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
  var vm = (TheViewModel)this.Resources["ViewModel"];
  Person p = (PersonObject) d;
  vm.Person = p;
}

您对DP和ViewModels的理解存在根本性的错误。您从不将DP与ViewModel一起使用,DP用于usercontrols,以公开ViewModel要绑定到的绑定。DP仅适用于DependencyObjects(用户控件是),因为DP的值存储在
DependencyObject
本身。谢谢您的评论。我知道将ViewModel转换为DO是个坏主意。我知道我不能把DP放在非DO中。我的问题是能够从用户控件中的DP在我的ViewModel normal属性中设置一个值。让我猜猜——您构建了一个用户控件来表示一个人,然后您为该用户控件创建了一个视图模型,该视图模型控制其中的封装逻辑?现在,如果是这样的话,想想我可能知道的原因。我创建了一个person data only类。我创建了一个视图模型,其中包含创建新的/保存到db/恢复/从db加载/maintain-a-list-of-persons/跟踪活动人员的逻辑。然后,我为Person创建了几个视图,其中一个视图允许我在Person的“应用程序范围”视图模型实例中查看活动人员,另一个视图向人员(不一定是活动人员)显示assoc数据。此特定的“TheViewModel”是非个人视图模型的一个实例,它需要一个人的知识来显示assoc-data-to-a-Person视图的数据。感谢您的评论。是的,你的方法是有效的。我没想到能通过暗号。我试图将绑定保留在xaml中。也许把它保存在xaml中是一种“卑鄙的行为”。事实上,我要撤销我的xaml攻击,你就照你的建议去做。你的方法不太老套,而我的方法却很老套——这使得我的方法不易维护,也不好用。谢谢,我的目标是维护性。
public static readonly DependencyProperty PersonProperty = 
    DependencyProperty.Register(
    "Person", typeof(PersonObject),
    typeof(MyUserControl), new FrameworkPropertyMetadata(null,
      FrameworkPropertyMetadataOptions.AffectsRender, 
      new PropertyChangedCallback(OnPersonChanged) )
    );

private static void OnPersonChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
  var vm = (TheViewModel)this.Resources["ViewModel"];
  Person p = (PersonObject) d;
  vm.Person = p;
}