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

时间:2015-02-25 15:26:44

标签: c# wpf wpf-4.0

我有以下对象定义:

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只显示一个CheckBox。想知道我哪里出错了。

2 个答案:

答案 0 :(得分:1)

您可以在不使用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>

答案 1 :(得分:0)

其中一种方式:

   <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>

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