将 WPF ListView 绑定到具有子集合的对象

Binding WPF ListView to an Object with Child Collection

我有以下对象定义:

public class FilterItem
{
    public string Type{get;set;}
    public List<string> Items{get;set;}
}

public class FiltersDataContext
{
    public string SearchText{get;set;}
    public List<FilterItem> Filters{get;set;}
}

我需要将 ListView 绑定到 FiltersDataContext.Filters.Items 子集合。

到目前为止,我的 xaml 看起来像这样:

<ListView Name="ResearchFilters" ItemsSource="{Binding FiltersDataContext.Filters}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <StackPanel  x:Name="FilterPanel">
                <CheckBox Content="{Binding Items, Mode=OneWay}" Tag="{Binding Path=Type, Mode=OneWay}" Checked="FilterCheckBox_OnCheck" Unchecked="FilterCheckBox_UnChecked" Click="FilteringResultSet"></CheckBox>
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

但是,ListView 只显示一个复选框。想知道我哪里出错了。

您可以在不使用 ListView 的情况下实现此目的,而是使用 ItemsControl

<ItemsControl ItemsSource="{Binding Path=Items}" ItemTemplate="{StaticResource CheckBoxItemsControlTemplate}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
</ItemsControl>

然后在你的资源字典中,添加这个

    <DataTemplate x:Key="CheckBoxTemplate">
        <CheckBox  Content="{Binding Items, Mode=OneWay}" Tag="{Binding Path=Type, Mode=OneWay}"/>
    </DataTemplate>

    <DataTemplate x:Key="CheckBoxItemsControlTemplate">
            <ItemsControl ItemsSource="{Binding Path=FiltersDataContext.Filters}" ItemTemplate="{StaticResource CheckBoxTemplate}">
            </ItemsControl>
    </DataTemplate>

</ResourceDictionary>

其中一种方式:

   <ListView Name="ResearchFilters" ItemsSource="{Binding Filters}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ItemsControl ItemsSource="{Binding Items}" Tag="{Binding Path=Type, Mode=OneWay}" BorderThickness="0">
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <StackPanel />
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>                              
                            <CheckBox Content="{Binding Mode=OneWay}" Tag="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl}, Path=Tag, Mode=OneWay}" Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked" Click="CheckBox_Click"></CheckBox>                               
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

您尝试将集合绑定为单个值。