我将同一个 UserControl 实例化了两次。两者都有单选按钮并共享 GroupName。当我选择一个时,所有其他人都取消选择,即使它们属于不同的 UserControl 实例。
如何避免这种 GroupName 冲突?
下面是一个简单的例子来说明这一点:
主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();
}
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>
最佳答案
加载用户控件后,您可以动态创建组名称值。
XAML:
<StackPanel>
<RadioButton GroupName="{Binding GroupNameValue}" x:Name="RadioOne" Content="RadioOne"/>
<RadioButton GroupName="{Binding GroupNameValue}" x:Name="RadioTwo" Content="RadioTwo"/>
</StackPanel>
View 模型:
private string groupNameValue = Guid.NewGuid().ToString();
public string GroupNameValue
{
protected get { return this.groupNameValue; }
set
{
this.SetProperty(ref this.groupNameValue, value);
}
}
SetProperty
是 INotifyPropertyChanged
的实现。
这里我用了Guid作为唯一性的保证,但您可以随意使用。
使用 C# 6.0 可以简化代码:
private string groupNameValue = Guid.NewGuid().ToString();
public string GroupNameValue => this.groupNameValue;
关于c# - WPF 单选按钮组与自定义用户控件发生冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38563541/