1

我正在使用 WPF 在 C# .NET 3.5 中开发应用程序。我在对话框中有一个列表框。当鼠标移到列表框中的某个项目上时,该项目会以蓝色背景突出显示。

当鼠标悬停在列表框中的某个项目上时,我想执行某些操作。所以我为列表框项添加了鼠标进入和鼠标离开事件处理程序,如下所示:

XAML 代码:

<ListBox  Name="listBox1" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="16,367,0,0" Width="181" Height="186" >
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <EventSetter Event="MouseEnter" Handler="listBox1_ListBoxItem_MouseEnter"/>
            <EventSetter Event="MouseLeave" Handler="listBox1_ListBoxItem_MouseLeave"/>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

C#代码:

private void listBox1_ListBoxItem_MouseEnter(object sender, MouseEventArgs e)
{
    ListBoxItem Item = sender as ListBoxItem;

    // Perform operations using Item.

    e.Handled = false;
}

private void listBox1_ListBoxItem_MouseLeave(object sender, MouseEventArgs e)
{
    ListBoxItem Item = sender as ListBoxItem;

    // Perform operations using Item.

    e.Handled = false;
}

添加事件处理程序后,当鼠标移到项目上时,列表框项目不再突出显示。如何使突出显示与事件处理程序一起工作?

感谢您提供的任何帮助。

4

2 回答 2

2

您正在覆盖 ListBoxItem 的默认样式,您应该使用 BasedOn 属性对其进行扩展

<ListBox  Name="listBox1" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="16,367,0,0" Width="181" Height="186" > 
    <ListBox.ItemContainerStyle> 
        <Style TargetType="ListBoxItem" BasedOn="{StaticResource {x:Type ListBoxItem}}"> 
            <EventSetter Event="MouseEnter" Handler="listBox1_ListBoxItem_MouseEnter"/> 
            <EventSetter Event="MouseLeave" Handler="listBox1_ListBoxItem_MouseLeave"/> 
        </Style> 
    </ListBox.ItemContainerStyle> 
</ListBox> 
于 2012-10-10T15:04:47.067 回答
1

丢失默认样式。您可以重新添加颜色。但我喜欢 Dtex 的答案。

        <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem">
                <EventSetter Event="MouseEnter" Handler="listBox1_ListBoxItem_MouseEnter"/>
                <EventSetter Event="MouseLeave" Handler="listBox1_ListBoxItem_MouseLeave"/>
                <Style.Resources>
                    <!-- Background of selected item when focussed -->
                    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
                        Color="Green"/>
                    <!-- Background of selected item when not focussed -->
                    <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}"
                        Color="LightGreen" />
                </Style.Resources>
            </Style>
        </ListBox.ItemContainerStyle>
于 2012-10-10T15:21:54.627 回答