2010-05-11 39 views
2

我遇到了一个令人讨厌的WPF绑定问题。基本上,我在我的UserControl的资源中声明了一个FrameworkElement,但是当父UserControl的DataContext发生更改时,该项似乎不会得到通知。获取WPF资源中已更改的DataContext的通知

基本上,在我的UserControl中,我在ItemsControl的ItemTemplate中有一个Popup。在那个Popup中,我需要绑定到父视图的ViewModel中的某些东西,所以我想出了我认为是一个聪明的技巧。以从CollectionViewSource的提示,我想我会我父母的视图模型只是绑定到资源,然后使用资源去视图模型从DataTemplate中,像这样:

<UserControl.Resources> 
     <cont:ViewModelSource Source="{Binding}" x:Key="ParentViewModel"/> 
    </UserControl.Resources> 

这样,以后我可以使用它像:

CommandParameter="{Binding ViewModel.OpenEntity, Source={StaticResource ParentViewModel}}" 

这一切都似乎工作除了,关于ViewModelSource在DataContext没有得到复位,当用户控件的DataContext获取复位。现在,我正在做这个工作:在UserControl的DataContextChanged事件中将资源的DataContext设置为代码隐藏。

我在Reflector中查看了一下CollectionViewSource如何做到这一点,但似乎没有做任何特别的事情。

任何人都知道为什么会发生这种情况,或者我可以如何解决这个问题?

回答

2

我有同样的问题,我找到了解决方案。

首先,我尝试将我的ViewModel设置为我的根元素的DataContext。错误。

然后我尝试将我的ViewModel设置为资源并将我的根元素的绑定源设置为资源。错误。

最后,我创建了一个IValueConverter,将Model(女巫是控件的DataContext)转换为ViewModel。然后我绑定我的根元素的DataContext与转换器。

<UserControl.Resources> 

    <local:PersonToControllerConverter x:Key="PersonToControllerConverter"/> 

    <!--<local:PersonController x:Key="controller" 
     Value="{Binding}" 
     Parent="{Binding Path=DataContext,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TreeViewItem}}}" 
     />--> 

</UserControl.Resources> 



<Border x:Name="root" BorderBrush="Black" BorderThickness="2" > 
    <Border.DataContext> 
     <MultiBinding Converter="{StaticResource PersonToControllerConverter}"> 
      <Binding/> 
      <Binding Path="DataContext" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type TreeViewItem}}"/> 
     </MultiBinding> 
    </Border.DataContext> 

    <!--DataContext="{Binding Source={StaticResource controller}}">--> 

    <!--<Border.DataContext> 
     <local:PersonController 
        Value="{Binding}" 
        Parent="{Binding Path=DataContext,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TreeViewItem}}}" 
        /> 
    </Border.DataContext>--> 

我认为,当在DataContext打破中的元素结合,当根元素上的datacontext的变化,它停在打破约束力。

1

也许你必须创建一个实现了INotifyPropertyChanged接口的中间对象。