我实例化了两个相同的UserControl。它们都有单选按钮并共享GroupName。当我选择其中一个时,所有其他单选按钮都会取消选择,即使它们属于不同的UserControl实例。
如何避免这种GroupName冲突?
以下是一个最小化的示例以说明此问题:
Main xaml
<Window x:Class="RadioDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<UserControl x:Name="First"/>
<UserControl x:Name="Second"/>
</StackPanel>
</Window>
主代码后端
public MainWindow()
{
InitializeComponent();
Loaded += MainWindow_Loaded;
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
First.Content = new MyRadio();
Second.Content = new MyRadio();
}
我的收音机 XAML
<UserControl x:Class="RadioDemo.MyRadio"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<StackPanel>
<RadioButton GroupName="G" x:Name="RadioOne" Content="RadioOne"/>
<RadioButton GroupName="G" x:Name="RadioTwo" Content="RadioTwo"/>
</StackPanel>
</UserControl>