Using Picture or Icon instead of DataGridCheckBoxC

2019-01-28 20:08发布

问题:

I want to change the CheckBox which is inside of a DataGridColumn into an image when it is checked and another when it is unchecked, How can i do ? Ps: My DataGridCheckBoxColumn is defined like this:

 <DataGridCheckBoxColumn Header="Priority" Binding="{Binding PRIORITY, Converter={StaticResource converter}}"/>

Converter is converting bytes to boolean.

回答1:

Use the ElementStyle and EditingElementStyle properties to create and set a different Template for the CheckBox which fits that.

e.g.

<DataGridCheckBoxColumn Binding="{Binding IsActive}">
    <DataGridCheckBoxColumn.ElementStyle>
        <Style TargetType="{x:Type CheckBox}">
            <Setter Property="IsEnabled" Value="False" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type CheckBox}">
                        <Image MaxWidth="32" MaxHeight="32">
                            <Image.Style>
                                <Style TargetType="{x:Type Image}">
                                    <Setter Property="Source" Value="Images/Error.ico" />
                                    <Style.Triggers>
                                        <DataTrigger Binding="{Binding IsChecked, RelativeSource={RelativeSource AncestorType=CheckBox}}" Value="True">
                                            <Setter Property="Source" Value="Images/Default.ico" />
                                        </DataTrigger>
                                    </Style.Triggers>
                                </Style>
                            </Image.Style>
                        </Image>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </DataGridCheckBoxColumn.ElementStyle>
</DataGridCheckBoxColumn>

This makes the column display an image based on IsChecked, the URIs are just hardcoded and the CheckBox is disabled because editing in the ElementStyle does not change any properties on the bound object. Its only purpose is to display the approriate image.

(The EditingElementStyle is not set here so if the user clicks the cell again to edit it a normal CheckBox appears which can be checked or unchecked.)