【问题标题】:ListBox ItemTemplate based on parent binding valueListBox ItemTemplate 基于父绑定值
【发布时间】:2012-07-29 23:14:07
【问题描述】:

基本上,我希望为我的列表项创建一个自定义模板。一个模板将使用复选框,而另一个将使用单选框。这是为了模拟何时允许或不允许多选。但是,我尝试了许多不同的方法,最有希望的是DataTemplateSelector,但是我需要创建一个依赖属性,以便我可以传入布尔值IsMultiSelect。但是,我需要在 Selector 中使用 DependencyObject,而我能得到的最接近的是 contentpresenter。我知道我可以以此为基础获得家长控制,但这似乎是一个黑客行为。有什么办法可以完成我想做的事情吗?

【问题讨论】:

    标签: c# wpf xaml .net-3.5 datatemplate


    【解决方案1】:

    我不完全确定我是否正确理解了所有内容,但这可能会有所帮助:

    <ListBox SelectionMode="Multiple">
    <!--<ListBox SelectionMode="Single">-->
        <ListBox.Items>
            <TextBlock Text="Test 1" />
            <TextBlock Text="Test 2" />
            <TextBlock Text="Test 3" />
            <TextBlock Text="Test 4" />
            <TextBlock Text="Test 5" />
            <TextBlock Text="Test 6" />
        </ListBox.Items>
        <ListBox.Style>
            <Style TargetType="{x:Type ListBox}">
                <Style.Resources>
                    <DataTemplate x:Key="SingleSelectionModeItemTemplate">
                        <RadioButton IsChecked="{Binding Path=IsSelected,
                                                         RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}},
                                                         Mode=TwoWay}"
                                     Content="{Binding}" />
                    </DataTemplate>
                    <DataTemplate x:Key="MultiSelectionModeItemTemplate">
                        <CheckBox IsChecked="{Binding Path=IsSelected,
                                                      RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}},
                                                      Mode=TwoWay}"
                                  Content="{Binding}" />
                    </DataTemplate>
                </Style.Resources>
                <Style.Triggers>
                    <Trigger Property="SelectionMode"
                             Value="Single">
                        <Setter Property="ItemTemplate" Value="{StaticResource SingleSelectionModeItemTemplate}" />
                    </Trigger>
                    <Trigger Property="SelectionMode"
                             Value="Multiple">
                        <Setter Property="ItemTemplate" Value="{StaticResource MultiSelectionModeItemTemplate}" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </ListBox.Style>
    </ListBox>
    

    【讨论】:

    • 比我的解决方案好多了:) 非常感谢简单的方法。我在 Style Triggers 周围跳舞,但由于某种原因,我从未真正想过使用 SelectionMode 作为触发器,因为我一直在尝试绑定。而且,我一直专注于设置 ItemTemplate 中的项目,而不是设置 ItemTemplate 本身。此外,RadioButton 需要一个 GroupName 才能使其成为单选,但这更多是我的实现细节,而不是问题的一部分:)
    猜你喜欢
    • 2013-02-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 2020-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多