Reputation: 6707
I instanciate the same UserControl twice. Both have Radiobuttons and share the GroupName. When I select one all others deselect even when they are part of a different UserControl Instance.
How can this GroupName Collision be avoided?
Here is a minimal example to illustrate the point:
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>
Main Codebehind
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>
Upvotes: 5
Views: 1732
Reputation: 1424
You can create group name value dynamically once user control is loaded.
XAML:
<StackPanel>
<RadioButton GroupName="{Binding GroupNameValue}" x:Name="RadioOne" Content="RadioOne"/>
<RadioButton GroupName="{Binding GroupNameValue}" x:Name="RadioTwo" Content="RadioTwo"/>
</StackPanel>
View-model:
private string groupNameValue = Guid.NewGuid().ToString();
public string GroupNameValue
{
protected get { return this.groupNameValue; }
set
{
this.SetProperty(ref this.groupNameValue, value);
}
}
Where SetProperty
is implementation of INotifyPropertyChanged
.
Here I used Guid as guarantee of the uniqueness, but you can use whether you want.
With C# 6.0 code can be simplified:
private string groupNameValue = Guid.NewGuid().ToString();
public string GroupNameValue => this.groupNameValue;
Upvotes: 8