如何在自定义ListView的列表项中有条件地插入复选框?

时间:2012-08-30 17:27:04

标签: wpf listview data-binding controltemplate contentcontrol

我尝试制作一个自定义ListView,根据需要填充每个列表项以及一些初始Checkbox。目前没有显示Checkbox,所以我想我的ContentControl内容的代码有点错误。

<ListView  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ListView.View>
    <GridView>
        <GridViewColumn>
            <GridViewColumn.CellTemplate>
                <DataTemplate>
                    <!-- Each list item: [Checkbox] Label -->
                    <StackPanel Orientation="Horizontal">
                        <!-- The code for the optional check box -->
                        <ContentControl>
                            <ContentControl.Style>
                                <Style TargetType="ContentControl">
                                    <Style.Triggers>
                                        <DataTrigger Binding="{Binding IsCheckable}" Value="True">
                                            <Setter Property="Template">
                                                <Setter.Value>
                                                    <ControlTemplate>
                                                        <CheckBox IsChecked="{Binding Path=SomeProperty}" />
                                                    </ControlTemplate>
                                                </Setter.Value>
                                            </Setter>
                                        </DataTrigger>
                                    </Style.Triggers>
                                </Style>
                            </ContentControl.Style>
                        </ContentControl>
                        <!-- The non-optional test label -->
                        <Label Content="Test Content" />
                    </StackPanel>
                </DataTemplate>
            </GridViewColumn.CellTemplate>
        </GridViewColumn>
    </ListView.View>
</ListView>

守则背后:

public partial class MyListView : ListView {
    public MyListView () {
        InitializeComponent();
    }

    public bool IsCheckable
    {
        get { return (bool)GetValue(IsCheckableProperty); }
        set { SetValue(IsCheckableProperty, value); }
    }

    public static readonly DependencyProperty IsCheckableProperty =
        DependencyProperty.Register(
        "IsCheckable", 
        typeof(bool), 
        typeof(AppropriatenessWidget), 
        new UIPropertyMetadata(false));
}

1 个答案:

答案 0 :(得分:0)

{Binding IsCheckable}绑定到DataContext而不是控件,例如:

{Binding IsCheckable,
         RelativeSource={RelativeSource AncestorType=local:MyListView}}

此外,我怀疑这种子类化方法是一个好主意,这可以通过基础DataContext轻松处理。