2012-01-11 56 views
0

我有一個TreeView數據綁定到一個CollectionViewSource組集合。這樣我就可以使用CollectionViewSource的強大功能來顯示數據,並且數據本身也具有層次結構,這就是爲什麼我需要TreeView。我有一個綁定到TreeView的SelectedItem的第二個控件。樹視圖中的集合視圖源分組 - 綁定錯誤

問題是,當選擇組標題時,程序崩潰,出現以下異常。

{"A TwoWay or OneWayToSource binding cannot work on the read-only property 'Name' of type 'MS.Internal.Data.CollectionViewGroupInternal'."} 

我的TreeView中的對象包含一個Name屬性,該屬性在另一個控件中雙向綁定。綁定引擎似乎找到該組的Name屬性並嘗試綁定到該屬性。我怎樣才能防止發生這種異常?我希望我的程序的其餘部分將它視爲在選擇組標題時沒有選擇任何內容,或者不允許一起選擇組標題。以下是代碼的簡化版本。

 <TreeView 
      x:Name="CustomersTree" 
      ItemsSource="{Binding CustomersViewSource.Groups}" 
      ItemTemplate="{StaticResource CustomerGroupsTemplate}"> 

     <MyUserControl DataContext="{Binding ElementName=CustomersTree, Path=SelectedItem, Mode=OneWay}" /> 

<HierarchicalDataTemplate x:Key="CustomerGroupsTemplate" ItemsSource="{Binding Path=Items}" ItemTemplate="{StaticResource CustomerTreeItemTemplate}"> 
    <TextBlock Text="{Binding Path=Name}"/> 
</HierarchicalDataTemplate> 

<HierarchicalDataTemplate x:Key="CustomerTreeItemTemplate" ItemsSource="{Binding Customers}"> 
    <StackPanel> 
     <Image Source="{Binding ImageSource}" /> 
     <TextBlock Text="{Binding Path=Name}" /> 
    </StackPanel> 
</HierarchicalDataTemplate> 

需要明確的是,錯誤的,據我可以告訴在CustomerGroupsTemplate的結合,並改變這種結合單向導致同樣的錯誤的結果。樹中的信息顯示了預期的方式,只有在選擇了組頭時纔會發生異常。

+0

您是否確定了哪兩個Name綁定導致了錯誤?您似乎有兩個這樣的綁定,一個在項目上,另一個在客戶上。順便說一句,你真的需要雙向綁定嗎? – 2012-01-11 18:38:28

回答

0

問題是用戶控件中雙向綁定的結果。我最終使用了一個轉換器來檢查被綁定對象的類型,如果它不是我想要的對象,則忽略它。