Using Picture or Icon instead of DataGridCheckBoxColumn in WPF

后端 未结 1 1897
甜味超标
甜味超标 2021-01-21 04:03

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

相关标签:
1条回答
  • 2021-01-21 04:25

    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.)

    Screencap

    0 讨论(0)
提交回复
热议问题