带有TextBlock和复选框的切换按钮
本文关键字:按钮 复选框 TextBlock 带有 | 更新日期: 2023-09-27 18:16:03
我试图创建一个WPF ToggleButton与一个文本框和一个复选框作为它的控制模板。
到目前为止我写的是:
<Style TargetType="{x:Type ToggleButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ToggleButton">
<StackPanel Orientation="Horizontal">
<TextBlock x:Name="toggleButtonTextBlock"
Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type ToggleButton}}, Path=Content}"/>
<CheckBox x:Name="toggleButtonCheckBox" VerticalAlignment="Center" Margin="2"
IsChecked="{Binding RelativeSource={RelativeSource AncestorType={x:Type ToggleButton}}, Path=IsChecked, Mode=TwoWay}" >
</CheckBox>
</StackPanel>
<ControlTemplate.Triggers>
<Trigger Property="ToggleButton.IsChecked" Value="True">
<Setter TargetName="toggleButtonTextBlock" Property="TextDecorations" Value="Underline"/>
<Setter TargetName="toggleButtonCheckBox" Property="IsChecked" Value="True"/>
</Trigger>
<Trigger Property="ToggleButton.IsChecked" Value="False">
<Setter TargetName="toggleButtonTextBlock" Property="TextDecorations" Value="{x:Null}"/>
<Setter TargetName="toggleButtonCheckBox" Property="IsChecked" Value="False"/>
</Trigger>
<Trigger Property="ToggleButton.IsChecked" Value="{x:Null}">
<Setter TargetName="toggleButtonTextBlock" Property="TextDecorations" Value="{x:Null}"/>
<Setter TargetName="toggleButtonCheckBox" Property="IsChecked" Value="False"/>
</Trigger>
<Trigger Property="ToggleButton.IsMouseOver" Value="True">
<Setter TargetName="toggleButtonTextBlock" Property="TextDecorations" Value="Underline"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
如果我单击ToggleButton的Text,文本将被正确地加下划线并选中CheckBox。但是,如果我点击CheckBox,文本没有正确地加下划线(并且ToggleButton没有更改为IsChecked=True)。
我如何得到ToggleButton是IsChecked=True(并有下划线的文本),当点击复选框?
我猜应该很简单,但由于我对XAML相当缺乏经验,这似乎超出了我的理解范围。
Thanks for your Help
你可以简化你的触发器。在WPF中,如果触发器的计算结果是false
,那么目标元素/属性将返回到之前的状态。您对toggleButtonCheckBox
的绑定足以将IsChecked
属性设置在ToggleButton
上;你不需要在触发器中设置它。
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ToggleButton">
<StackPanel Orientation="Horizontal">
<TextBlock x:Name="toggleButtonTextBlock"
Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type ToggleButton}}, Path=Content}"/>
<CheckBox x:Name="toggleButtonCheckBox"
VerticalAlignment="Center"
Margin="2"
IsChecked="{Binding RelativeSource={RelativeSource AncestorType={x:Type ToggleButton}}, Path=IsChecked, Mode=TwoWay}" >
</CheckBox>
</StackPanel>
<ControlTemplate.Triggers>
<!-- Will return to previous state if false -->
<Trigger Property="ToggleButton.IsChecked" Value="True">
<Setter TargetName="toggleButtonTextBlock"
Property="TextDecorations"
Value="Underline"/>
</Trigger>
<Trigger Property="ToggleButton.IsMouseOver" Value="True">
<Setter TargetName="toggleButtonTextBlock"
Property="TextDecorations"
Value="Underline"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>