C#WPF:添加鼠标输入和鼠标离开事件处理程序后,ListBox项目未突出显示

时间:2012-10-10 12:09:27

标签: c# .net wpf events xaml

我正在使用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;
}

添加事件处理程序后,当鼠标悬停在项目上时,列表框项目不再突出显示。如何使用事件处理程序进行突出显示?

感谢您提供任何帮助。

2 个答案:

答案 0 :(得分: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> 

答案 1 :(得分: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>