鼠标悬停时WPF列表框选择项目

Chr*_*ath 8 .net wpf xaml

我正在尝试为列表框创建一个样式,当项目上有鼠标时,它会将所选项目设置为项目.

任何提示?

Mat*_*ton 13

您可以使用ListBox本身中影响其所有项目的样式来执行此操作:

<ListBox.Resources>
    <Style TargetType="ListBoxItem" BasedOn="{StaticResource {x:Type ListBoxItem}}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding IsMouseOver,RelativeSource={RelativeSource Self}}" 
                         Value="True">
                <Setter Property="IsSelected" Value="True" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</ListBox.Resources>
Run Code Online (Sandbox Code Playgroud)

当IsMouseOver属性为true时,这会将项目上的IsSelected属性设置为true.如果您的ListBox不是多选的,它会以您期望的方式工作.

  • 这听起来更像是属性值优先问题.例如,本地值(绑定被视为本地)具有比样式触发器更高的优先级.本文解释了DP的价值优先权:http://msdn.microsoft.com/en-us/library/ms743230.aspx (3认同)