簡體   English   中英

C#WPF:添加鼠標輸入和鼠標離開事件處理程序后,ListBox項目未突出顯示

[英]C# WPF: ListBox item not getting highlighted after adding mouse enter and mouse leave event handlers

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

添加事件處理程序后,當鼠標懸停在項目上時,列表框項目不再突出顯示。 如何使用事件處理程序進行突出顯示?

感謝您提供的任何幫助。

您正在覆蓋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> 

丟失默認樣式。 您可以重新添加顏色。但我喜歡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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM