2010-05-11 107 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接口的中間對象。