Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wpf datatrigger bind to method

I have a method that returns true or false.

I want this method to be binded to my DataTrigger

       <DataGrid ItemsSource="{Binding Source={StaticResource SmsData}, XPath=conv/sms}">
        <DataGrid.RowStyle>
            <Style TargetType="{x:Type  DataGridRow}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Path=check}" Value="true">
                        <Setter Property="Foreground" Value="Black" />
                        <Setter Property="Background" Value="Blue" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </DataGrid.RowStyle>
    </DataGrid>

if returned value is "true", then do the setter...

My Code:

public MainWindow()
{
    DataContext = this;
    InitializeComponent();
}


public string check
{
    get
    {
       return "true";
    }
}

How can I get this working ? I get an error now (in runtime, not crashing my program): BindingExpression path error: 'check' property not found on 'object' ''XmlElement'

like image 649
keno Avatar asked Oct 05 '22 14:10

keno


1 Answers

The DataContext of the RowStyle is an item in the ItemsSource of the DataGrid. In your case, this is an XMLElement. To Bind to the DataContext of the DataGrid, you have to refer to the DataGrid by ElementName, and the Path is the element's DataContext. Like this:

   <DataGrid Name="grid" ItemsSource="{Binding ... 
    <DataGrid.RowStyle>
        <Style TargetType="{x:Type DataGridRow}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=grid, Path=DataContext.check}" Value="true">
                    <Setter Property="Foreground" Value="Black" />
                    <Setter Property="Background" Value="Blue" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.RowStyle>
</DataGrid>
like image 191
AndyClaw Avatar answered Oct 10 '22 01:10

AndyClaw