WPF DataTrigger不适用于ViewModel属性

时间:2016-06-09 05:25:21

标签: wpf xaml caliburn.micro datatrigger

我在XAML中有一个usercontrol,如下所示:

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

和ViewModel类:

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是一个包含一些属性的类:FirstName,LastName,Age ...

但它不起作用,因为DataRowChanged不是Person的成员。如果我在XAML中将DataRowChanged的{​​{1}}属性更改为Person,则会有效。 任何人都可以帮助我。提前谢谢。

1 个答案:

答案 0 :(得分:3)

试试这个:

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