Wieknot
Wieknot

Reputation: 99

WPF trigger based on property a cell is bound too

So I would like to change the background color of any dataGridCell.

The DateGrid.ItemsSource is bound to a class something like this.

public class OldData
{
   public Cell Name{ get; set; }
}

public class Cell
{
   public object Value  { get; set; }
   public Boolean DoesMatch { get; set; }    
}

I have been trying to set up a cell template with a trigger on DoesMatch, but wpf cannot seem to find it.

<DataGrid x:Name="dgNew" AutoGenerateColumns="True" >
    <DataGrid.CellStyle>
        <Style TargetType="DataGridCell">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=DoesMatch, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type lib:Cell}}}" Value="False">
                    <Setter Property="Background" Value="#FFF35656" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
     </DataGrid.CellStyle>
 </DataGrid>

I have tried several variations of the template, but they spit out Data errors into my output window, and of coerce, my cell backgrounds don't change. :)

WPF Output Error:

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='CsvDataCompareTool.Lib.Cell', AncestorLevel='1''. BindingExpression:Path=DoesMatch; DataItem=null; target element is 'DataGridCell' (Name=''); target property is 'NoTarget' (type 'Object')

Any help would be greatly appreciated.

Update:

tried it without relativeSource

<DataTrigger Binding="{Binding Path=DoesMatch}" Value="False">
    <Setter Property="Background" Value="#FFF35656" />
</DataTrigger>

Error:

System.Windows.Data Error: 40 : BindingExpression path error: 'DoesMatch' property not found on 'object' ''NewData' (HashCode=53750044)'. BindingExpression:Path=DoesMatch; DataItem='NewData' (HashCode=53750044); target element is 'DataGridCell' (Name=''); target property is 'NoTarget' (type 'Object')

Upvotes: 1

Views: 1218

Answers (1)

Peter Hansen
Peter Hansen

Reputation: 8907

The datacontext of each cell in the DataGrid will be set to the OldData object it represents, so you should be able to bind directly to it without using a RelativeSource binding.

But since DoesMatch is not a property on OldData but on Cell, you have to bind to Name.DoesMatch instead, like this:

<DataGrid x:Name="dgNew" 
          AutoGenerateColumns="True" 
          ItemsSource="{Binding DataCollection}">
    <DataGrid.CellStyle>
        <Style TargetType="DataGridCell">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=Name.DoesMatch}" Value="False">
                    <Setter Property="Background" Value="#FFF35656" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.CellStyle>
</DataGrid>

Upvotes: 1

Related Questions