Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a viewmodel property when Property Trigger fires

Tags:

c#

wpf

c#-4.0

xaml

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>
like image 395
Mike Caron Avatar asked Aug 27 '13 19:08

Mike Caron


1 Answers

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

like image 183
Adi Lester Avatar answered Oct 06 '22 05:10

Adi Lester