WPF-单选按钮控制模板绑定“;IsChecked";不起作用

WPF-单选按钮控制模板绑定“;IsChecked";不起作用,wpf,xaml,controltemplate,ischecked,Wpf,Xaml,Controltemplate,Ischecked,我有一个如下所示的控件模板,我想在用户选择单选按钮时获得IsChecked属性 但当用户选择单选按钮“A”时,IsChecked属性仍然显示false。为什么? <ControlTemplate x:Key="RadioBtnTemplate" TargetType="{x:Type RadioButton}"> <Grid> <StackPanel Margin="5"> <RadioButton Name="temp

我有一个如下所示的控件模板,我想在用户选择单选按钮时获得
IsChecked
属性

但当用户选择单选按钮“A”时,
IsChecked
属性仍然显示false。为什么?

<ControlTemplate x:Key="RadioBtnTemplate" TargetType="{x:Type RadioButton}">
   <Grid>
     <StackPanel Margin="5">
         <RadioButton Name="tempbtn" IsChecked="{TemplateBinding IsChecked}" FontFamily="Segoe UI" FontSize="18.667" Content="{TemplateBinding Content}" GroupName="{TemplateBinding GroupName}"/>
      </StackPanel>
    </Grid>
</ControlTemplate>

我使用这个模板:
<RadioButton GroupName="CG" x:Name="_rdoBtnA" Content="A" Template="{DynamicResource RadioBtnTemplate}" IsChecked="True"/>
<RadioButton GroupName="CG" x:Name="_rdoBtnB" Content="B" Template="{DynamicResource RadioBtnTemplate}" />
<RadioButton GroupName="CG" x:Name="_rdoBtnC" Content="C" Template="{DynamicResource RadioBtnTemplate}" />


您可以这样使用它:

<StackPanel Orientation="Horizontal">
    <StackPanel.Resources>
        <ControlTemplate x:Key="ButtonAsSwatchTemplate">    
            <Border x:Name="SwatchBorder" BorderThickness="1">
                <Rectangle Fill="{TemplateBinding Property=Background}" Width="15" Height="15" />
            </Border>
        <ControlTemplate.Triggers>
            <Trigger Property="ToggleButton.IsChecked" Value="True">
                <Setter TargetName="SwatchBorder" Property="BorderBrush" Value="Yellow" />
            </Trigger>
        </ControlTemplate.Triggers>
            </ControlTemplate>
        </StackPanel.Resources>
    <RadioButton Template="{StaticResource ButtonAsSwatchTemplate}"
        GroupName="CropGuidesColourRadioButtonGroup"
        IsChecked="{Binding Checked}" Margin="2" Background="Red" />
    <RadioButton Template="{StaticResource ButtonAsSwatchTemplate}"
        GroupName="CropGuidesColourRadioButtonGroup" 
        IsChecked="{Binding Checked}" Margin="2" Background="Black" />
</StackPanel>


摘自

如果我们以您的示例为例,那么您有两个问题导致您看到的问题

第1期: 首先,您的设计创建了六个而不是三个控件。
中的三个,然后是作为控件模板的一部分创建的三个。所有六个单选按钮现在都链接为
GroupName=“CG”
组的一部分

正如您所知,因为它们都属于相同的
CG
组,所以六个单选按钮中只有一个可以将
IsChecked
属性设置为
True
。三个命名控件
\u rdoBtnA
\u rdoBtnB
\u rdoBtnC
甚至在屏幕上都不可见,因此它们永远不能设置为
(在
的情况下,
XAML
声明的
True
绑定模板控件时立即设置为
False

要解决此问题,请从控件模板定义中删除
GroupName=“{TemplateBinding GroupName}”
,只保留组中的三个顶级单选按钮

问题2:这是我认为您问题的根源所在。
IsChecked={TemplateBinding IsChecked}
只是一种
方式的绑定,不会以另一种方式更新。要使绑定
双向
需要使用绑定定义的长版本,
IsChecked=”{Binding已检查,RelativeSource={relativesourcetemplatedparent},Mode=TwoWay}“

现在,通过进行这两个更改,控件模板将变成这样



RadioButton模板中的RadioButton?对我来说没有意义。你想实现什么?事实上,我只是想让每个RadioButton看起来都一样,那还有其他好的设计吗?哦!非常感谢你的帮助,让我明确了绑定的概念!!