tags:

views:

653

answers:

1

I'm trying to make a style for a listbox which will set the selected item to an item when the item has the mouse on it.

Any hints?

+2  A: 

You can do it using a style in the ListBox itself that affects all its items:

<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>

That'll set the IsSelected property on the item to true when the IsMouseOver property is true. Provided your ListBox isn't multi-select it works the way you'd expect.

Matt Hamilton
Works well. Strangely, when I Data bind to SelectedItem and the item it binds to has a value beforehand it the mouse over won't select that item (if you leave and come back). Any ideas?
Chris McGrath
That's pretty strange. Out of interest, try adding a setter to set IsSelected to false in the style (outside of the trigger).
Matt Hamilton
Nope, doesn't fix it. I can work around it (by not having any selected at startup), but it's something I wouldn't mind figuring out.
Chris McGrath
Not entirely sure, but the properties only cause binding updates when they change, so if the UI gets out of sync with the IsSelected property in some way, setting it to true while already true will not cause the UI to update. I had problems like this when I had multiple ListBoxes with different Items all binding to a common Selection. Setting the Selection would only cause the SelectedItem to change if the ListBox contained the item, which means the next time I clicked on the item in the ListBox, IsSelected would not change and so the TwoWay binding to Selection was not updated.
Dan Bryant
This sounds more like a property value precedence issue to me. For instance, local values (Bindings are considered local) have a higher precedence than style triggers. This article explains the value precedence of DPs: http://msdn.microsoft.com/en-us/library/ms743230.aspx
Abe Heidebrecht