11
votes

I have a ListView with a View Model. The ItemsSource is a collection of objects in the View Model. A property exists on the View Model for some flag, IsFlagOn. I want to set that property in the View Model to True when the ListViewItem detects a IsMouseOver. Other UI elements are then bound to this same property so that the view changes as MouseOver is toggled.

How would I accomplish this in XAML?

I would imagine something like this (but this breaks):

<Style> <!-- on the ListViewItem -->
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="DataContext.IsFlagOn" Value="True" />
        </Trigger>
    </Style.Triggers>
</Style>

UPDATE:

The error is

Cannot resolve the Style Property 'IsFlagOn'. Verify that the owning type is the Style's TargetType, or use Class.Property syntax to specify the Property.

UPDATE(2):

Here's a bit more of the existing XAML (following). You can see that the ListView is bound with a property of the VM, AllItems. Important to note that each item in the list is a VM, where each column is bound. So is the ItemContainerStyle binding against the ListView VM or the Item VM?

<ListView Itemssource="{Binding AllItems}">
    <ListView.ItemContainerStyle>
        <Style> <!-- on the ListViewItem -->
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="DataContext.IsFlagOn" Value="True" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </ListView.ItemContainerStyle>
    <ListView.View>
        <GridView>
            <!-- ... -->
        </GridView>
    </ListView.View>
</ListView>
1
but this breaks with what exception? Is IsFlagOn a dependency property?PoweredByOrange
Error is "Type DataContext is not found". View model is plain class implementing INotifyPropertyChanged, so IsFlagOn is not a dependency property.Mike Caron
OK, so what is the actual exception?PoweredByOrange
Are you applying this style on the ListView, and yet want the "IsMouseOver" property change to be detected for each individual ListViewItem? The way I see it, this will react whenever the mouse is over the ListView itself, not any particular ListViewItem. Is this what you really want?Samir
@Samir see update. It's a style on ListViewItem.Mike Caron

1 Answers

8
votes

This is pretty much what OneWayToSource binding mode was made for - being able to just update the view model from the view. However, since IsMouseOver is a read-only property, you won't be able to do this (due to a bug in WPF):

<Setter Property="IsMouseOver" Value="{Binding Path=IsFlagOn, Mode=OneWayToSource}" />

There are ways to get around it though. Some of them are described here: OneWayToSource binding from readonly property in XAML