动态更改复选框样式为默认值

时间:2017-04-05 20:26:18

标签: wpf xaml

我使用datatrigger将复选框Image Source更改为图标。

<CheckBox Content="An Image CheckBox Label" Foreground="Black" Margin="73,103,27,142" IsThreeState="True" >
    <CheckBox.Template>
        <ControlTemplate TargetType="{x:Type CheckBox}">
            <StackPanel Orientation="Horizontal">
                <Image>
                    <Image.Style>
                        <Style>
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding IsChecked, RelativeSource={RelativeSource AncestorType={x:Type CheckBox}}}" Value="True">
                                    <Setter Property="Image.Source" Value="/Images/Checkbox.ico" />
                                </DataTrigger>
                                <DataTrigger Binding="{Binding IsChecked, RelativeSource={RelativeSource AncestorType={x:Type CheckBox}}}" Value="False">
                                    <Setter Property="Image.Source" Value="/Images/CheckboxUncheck.ico" />
                                </DataTrigger>
                                <DataTrigger Binding="{Binding IsChecked, RelativeSource={RelativeSource AncestorType={x:Type CheckBox}}}" Value="{x:Null}">
                                    <Setter Property="Image.Source" Value="/Images/delete_12x12.png" />
                                    <Setter Property="Image.Width" Value="10" />
                                    <Setter Property="Image.Height" Value="10" />
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </Image.Style>
                </Image>
                <ContentPresenter Content="{TemplateBinding Content}"  Margin="5,0,0,0" />
            </StackPanel>
        </ControlTemplate>
    </CheckBox.Template>
</CheckBox>

当isChecked = False Value="False或inderterminate Value="{x:Null}时,是否可以将复选框样式(或图像)设置为默认状态?

1 个答案:

答案 0 :(得分:1)

如果您只想在选中CheckBox时应用自定义模板,则可以将Style Trigger应用于CheckBox

<CheckBox Content="An Image CheckBox Label" Foreground="Black" Margin="73,103,27,142" IsThreeState="True" >
    <CheckBox.Style>
        <Style TargetType="CheckBox">
            <Style.Triggers>
                <Trigger Property="IsChecked" Value="True">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type CheckBox}">
                                <StackPanel Orientation="Horizontal">
                                    <Image Source="/Images/Checkbox.ico" />
                                    <ContentPresenter Content="{TemplateBinding Content}"  Margin="5,0,0,0" />
                                </StackPanel>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Trigger>
            </Style.Triggers>
        </Style>
    </CheckBox.Style>
</CheckBox>