0

我尝试制作一个自定义的 ListView,如果需要,它会用一些东西和一个初始 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));
}
4

1 回答 1

0

{Binding IsCheckable}绑定到DataContext非控件,例如使用:

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

我也怀疑这种子类化方法是否是个好主意,这可以通过底层轻松处理DataContext​​。

于 2012-08-30T17:49:15.703 回答