简体   繁体   中英

WPF ListBoxItem IsMouseOver

I have a ListBox, which on mousing over an item shows a delete button for that item. The problem is that the IsMouseOver triggers about 4 pixels into the highlighted item, so when mousing over multiple items, instead of the delete button seeming to move up and down with you, it flickers in the gaps between the items. Is there anyway to make IsMouseOver respond to the whole item?

<ListBox Name="lstLength" ItemsSource="{Binding Source={StaticResource lengths}}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <DockPanel LastChildFill="True" Height="22">
                <Button DockPanel.Dock="Right" Name="btnDelete" Content="X" Tag="{Binding}" Click="DeleteLength" Visibility="Collapsed" />
                <TextBlock Text="{Binding}" />
            </DockPanel>

            <DataTemplate.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter TargetName="btnDelete" Property="Visibility" Value="Visible" />
                </Trigger>
            </DataTemplate.Triggers>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Each one of your items will be contained within a ListBoxItem , this is what gives the ~4 pixels between each item. It also provides the highlight and selection styling. You can style the listBoxItem via the ListBox.ItemContainerStyle property. Move your trigger to the item container and it should work as desired.

You could use a DataTrigger directly on the button (or try to apply the same RelativeSource binding in the place it is):

<Style TargetType="{x:Type Button}">
    <DataTrigger Binding="{Binding IsMouseOver, RelativeSource={RelativeSource AncestorType=ListBoxItem}}"
                 Value="True">
          <!-- ... -->
    </DataTrigger>
</Style>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM