树视图中的集合视图源分组-绑定错误

本文关键字:视图 错误 绑定 集合 | 更新日期: 2023-09-27 18:20:12

我有一个TreeView数据绑定到CollectionViewSource Groups集合。这样我就可以使用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中绑定的结果,将此绑定更改为OneWay也会导致相同的错误。树中的信息以预期的方式显示,只有当选择了组标头时才会发生异常。

树视图中的集合视图源分组-绑定错误

问题是用户控件内双向绑定的结果。我最终使用了一个转换器来检查要绑定的对象的类型,如果它不是我想要的对象,则忽略它。