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

时间:2016-02-17 21:27:43

标签: xaml mvvm

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

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

最初我试过这个:

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

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

这会产生错误,因为TheViewModel不是DependencyObject。我宁愿不把它变成一个依赖对象,因为我不想让那些讨厌的“只做UI线程中的东西”问题。

将DP从UC绑定到XAML中实例化的VM的非DP属性的干净方法是什么?

我目前有一个,可能是hacky,也许是不干净的解决方案。我还没有运行它,但我相信它应该工作。以下是:

在TheViewModel中,我创建了2个附加属性。人和VM。在UC中,我创建了一个Dud Separator,它是Collapsed,Person-AP和VM-AP设置在其中。在Person-AP的更改事件中,我从VM-AP获取VM,然后相应地将其设置为Patient non-dp-p。

...snip...
<DockPanel>
    <!--Hacky Separator used only as a binding object to help the VM-->
    <Separator DockPanel.Dock="Top" Visibility="Collapsed"
            vms:TheViewModel.Person="{Binding ElementName=uiControlMe, Path=Person}"
            vms:TheViewModel.VM="{Binding Source={StaticResource ViewModel}}" />
...snip...

有更好的方法吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

当Dependency属性更改时,获取View Model资源并在View Model上设置属性。

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;
}
相关问题