Question

I have a simple DataGrid with a column of text and a column with a checkbox, and based on some fairly complicated conditions I want to style the text AND set or disable the checkbox. I can implement the same trigger for both cells but that seems like bloat and unnecessary, I am looking for the most efficient way to do this. It seems like it should be possible, I am just at a complete loss.

        <DataGrid>
            <DataGrid.Columns>
                <DataGridTemplateColumn>
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Label Name="needToStyleThis" VerticalAlignment="Center"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTemplateColumn Header="" Width="Auto">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <CheckBox x:Name="needToSetIsChecked"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
Was it helpful?

Solution

This is generally achieved with data binding. If you add a bool property to your data class, then you can do your complicated conditions in the property setters of the class. In the class, you can change any of the property values dependant on any other value easily. Maybe something like this:

public string Text
{
    get { return text; }
    set 
    {
        text = value;
        NotifyPropertyChanged("Text");
        IsEnabled = text == "some value" && otherSomeConditions == true;
    }
}

Then you could data bind that to the Checkbox.IsEnabled property like this:

<DataGrid>
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Label Name="needToStyleThis" VerticalAlignment="Center"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTemplateColumn Header="" Width="Auto">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <CheckBox IsEnabled="{Binding IsEnabled}" ... />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top