我将同一个UserControl实例化两次。两者都有Radiobuttons并共享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>
答案 0 :(得分:4)
加载用户控件后,您可以动态创建组名称值。
XAML:
<StackPanel>
<RadioButton GroupName="{Binding GroupNameValue}" x:Name="RadioOne" Content="RadioOne"/>
<RadioButton GroupName="{Binding GroupNameValue}" x:Name="RadioTwo" Content="RadioTwo"/>
</StackPanel>
查看模型:
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;