Quan Nguyen
Quan Nguyen

Reputation: 582

WPF DataTrigger doesn't work with ViewModel property

I have a usercontrol in XAML as below:

<UserControl x:Class="Presentation.Views.PersonListView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:cal="clr-namespace:Caliburn.Micro;assembly=Caliburn.Micro.Platform"
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300"
         MinWidth="300" MinHeight="300">
<Grid>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="10"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <TextBlock Grid.Row="0" Text="List of Persons"/>
        <DataGrid SelectionMode="Single" SelectionUnit="FullRow" Grid.Row="2" x:Name="Persons" IsReadOnly="True"
                  cal:Message.Attach="[Event MouseDoubleClick] = [Action OpenPersonDetail()]" SelectedItem="{Binding SelectedPerson}">
            <DataGrid.RowStyle>
                <Style TargetType="DataGridRow">
                    <Setter Property="Background" Value="White"/>
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding DataRowChanged}" Value="True">
                            <Setter Property="Background" Value="Red"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </DataGrid.RowStyle>
        </DataGrid>
    </Grid>
</Grid>

And ViewModel class:

public class PersonListViewModel
{
    ...

    private bool m_DataRowChanged;

    public IObservableCollection<Person> Persons {
        get;
        set;
    }

    public bool DataRowChanged
    {
        get { return m_DataRowChanged; }
        set
        {
            m_DataRowChanged = value;
            NotifyOfPropertyChange(() => DataRowChanged);
        }
    }

    public void Handle(Person p)
    {
        GetPersonList();
        foreach (var item in Persons)
        {
            if (!item.Version.Equals(p.Version))
            {
                DataRowChanged = true;
                break;
            }
        }
    }
}

Person is a class which contains some properties: FirstName, LastName, Age...

But it doesn't work because DataRowChanged is not a member of Person. It will work if I change DataRowChanged by one of property of Person in XAML. Anyone can help me. Thanks in advance.

Upvotes: 1

Views: 1822

Answers (1)

Jai
Jai

Reputation: 8363

Try this:

<DataTrigger Binding="{Binding DataContext.DataRowChanged,
                       RelativeSource={RelativeSource AncestorType=UserControl}}"
             Value="True">
    <Setter Property="Background" Value="Red"/>
</DataTrigger>

Upvotes: 3

Related Questions