具有与RadioButton IsChecked属性类似功能的自定义控件

本文关键字:功能 自定义控件 属性 RadioButton IsChecked | 更新日期: 2023-09-27 18:16:46

我试图了解RadioButton中的IsChecked属性是如何工作的,因为我正在构建一个具有类似行为的自定义控件。

我需要的信息是当其他RadioButton被检查时,RadioButton如何自动将IsChecked变为false

参见示例:

<StackPanel>
    <RadioButton Content="Info 1" IsChecked="True" />
    <RadioButton Content="Info 2" />
</StackPanel>

如果我在RadioButton"Info 2"中点击,其他电台将自动转为未选中。

但是如果无线电在不同的StackPanel中,像这样:

<StackPanel>
    <StackPanel>
        <RadioButton Content="Info 1.1" IsChecked="True" />
        <RadioButton Content="Info 1.2" />
    </StackPanel>
    <StackPanel>
        <RadioButton Content="Info 2.1" IsChecked="True" />
        <RadioButton Content="Info 2.2" />
    </StackPanel>
</StackPanel>

Info 1.1被点击时,Info 2.1仍然被选中。

我的自定义控件需要这个行为。最干净的方法是什么?

具有与RadioButton IsChecked属性类似功能的自定义控件

RadioButton是一个控件,通常用作一组RadioButton控件中的项。RadioButton控件继承自ToggleButton类,而ToggleButton类又继承自ButtonBase。因为RadioButton控件继承自ToggleButton,所以它们使用户能够更改选择。当对RadioButton元素进行分组时,按钮是互斥的。用户一次只能在RadioButton组中选择一个项目。在您的示例中,具有Info 1.1和Info 1.2内容的单选按钮因此共享相同的父控件它们是分组的,这意味着一次只检查一个单选按钮,而具有信息1.1和信息2.1内容的单选按钮不共享相同的父控件,这意味着它们没有分组所以当Info 1.1被选中时,它不会对Info2.1产生任何影响

您可以从RadioButton派生您的自定义控件。这样,当您单击与同一父级分组的复选框之一时,IsChecked的值将被切换。