在列表框中选择时,WPF会更改datatemplate的可视状态

Mar*_*ark 4 c# wpf listbox visualstatemanager

如果我有一个包含自定义用户控件ListBox的基本WPF ,ItemTemplate我如何告诉用户控件在DataTemplate更改其视觉状态时选择ListBox

非常感谢您提供的任何帮助

Ric*_*key 7

您可以设置ListBoxItem要在IsSelected属性上触发的样式.这是一个例子:

然后你像这样使用它:

<ListBox ItemContainerStyle="{StaticResource yourListBoxItemStyle}">
Run Code Online (Sandbox Code Playgroud)

或直接在ListBox自己:

<ListBox.ItemContainerStyle>
    <Style TargetType=”ListBoxItem”>
        ...
    </Style>
</ListBox.ItemContainerStyle>
Run Code Online (Sandbox Code Playgroud)

编辑:

下面是一个完整的示例,其中包含a ItemTemplate和a ItemContainerStyle,它将半透明图层放在所选项目的顶部.

<Grid>
    <Grid.Resources>
        <x:Array Type="sys:String" x:Key="sampleData">
            <sys:String>Red</sys:String>
            <sys:String>Green</sys:String>
            <sys:String>Blue</sys:String>
        </x:Array>
        <DataTemplate x:Key="listBoxItem">
            <Rectangle Fill="{Binding}" Width="100" Height="100"/>
        </DataTemplate>
        <Style TargetType="ListBoxItem" x:Key="listBoxItemStyle">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ListBoxItem">
                        <Grid>
                            <ContentPresenter />
                            <Rectangle x:Name="Rectangle" Fill="Black" Opacity="0"/>
                        </Grid>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsSelected" Value="true">
                                <Setter TargetName="Rectangle" Property="Opacity"
                                    Value="0.5"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Grid.Resources>
    <ListBox
        ItemsSource="{StaticResource sampleData}"
        ItemTemplate="{StaticResource listBoxItem}"
        ItemContainerStyle="{StaticResource listBoxItemStyle}"
        />
</Grid>
Run Code Online (Sandbox Code Playgroud)

编辑

评论之后,这是使用"统一"模板的版本:

<Style TargetType="ListBoxItem" x:Key="listBoxItemStyle">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ListBoxItem">
                <Grid>
                    <Rectangle Name="Rectangle" Fill="{Binding}" Width="100" Height="100" Opacity="1"/>
                </Grid>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsSelected" Value="true">
                        <Setter TargetName="Rectangle" Property="Opacity"
                            Value="0.5"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
Run Code Online (Sandbox Code Playgroud)