Mr J
Mr J

Reputation: 2963

C# WPF DataGrid change cell icon resource programmatically

I've never used a DataGrid in C# before (and done little C#) and I'm struggling to change a DataGrid cell icon I've set in XAML. By default its set to a Dynamic resource of appbar_question and upon certain conditions being met I'd like to be able to change it to a resource of appbar_check (I'm using the mahapps icons).

XAML code

    <DataGrid x:Name="dataGrid" AutoGenerateColumns="False" ItemsSource="{Binding}">

        <DataGrid.Columns>

            <DataGridTextColumn HeaderStyle="{StaticResource CenterMe}" Header="Website" Binding="{Binding Website}">
                    <DataGridTextColumn.CellStyle>
                    <Style>
                        <Setter Property="FrameworkElement.HorizontalAlignment" Value="Center"/>
                    </Style>
                    </DataGridTextColumn.CellStyle>
            </DataGridTextColumn>

            <DataGridTemplateColumn HeaderStyle="{StaticResource CenterMe}" Header="Status" >
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Button Click="ShowStatus">
                            <Button.Template>
                                <ControlTemplate>
                                    <Rectangle Width="16" Height="16" Fill="{Binding RelativeSource={RelativeSource AncestorType=Button}, Path=Foreground}">
                                        <Rectangle.OpacityMask>
                                            <VisualBrush Stretch="Fill" Visual="{DynamicResource appbar_question}" />
                                        </Rectangle.OpacityMask>
                                    </Rectangle>
                                </ControlTemplate>
                            </Button.Template>
                        </Button>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

        </DataGrid.Columns>

    </DataGrid>

First I tried to access the cell directly but I see DataGrids in WPF like you to bind to an object(s) then access them as items and change properties in that object. However I tried doing that but couldn't figure out how to bind to a resource in my object?

Upvotes: 0

Views: 1063

Answers (1)

Try use DataTemplate.Triggers: 1. Name your VisualBrush:

     <VisualBrush x:Name="myBrush"...
  1. Add DataTemplate.Triggers:

    <DataTemplate.Triggers>
       <DataTrigger Binding="{Binding to_my_property}" Value="my_condition">
          <Setter TargetName="myBrush" Property="Visual" Value="{DynamicResource appbar_check}"/>
       </DataTrigger>
    </DataTemplate.Triggers>
    

Hope it helps.

Upvotes: 1

Related Questions