Reputation: 27
I have a WPF UserControl named YesNoSelection, containing a Label and two RadioButtons named rbnYes and rbnNo. I would like to Automatically set the RadioButton GroupName property to the name of my control, so I used:
public YesNoSelection()
{
InitializeComponent();
rbnYes.GroupName = this.Name;
rbnNo.GroupName = this.Name;
}
The control is added in designer like this:
<local:YesNoSelection x:Name="selOnTop" Label="Always on top" Margin="2,2,2,2" Grid.Row="0"/>
However, it does not work. After some debugging, I found that
this.Name
always returns empty. In the designer, it does not let me set the regular Name property, just x:Name, because the class is defined locally (I think?).
I have done a lot of work in WinForms, but am quite new to WPF. Is there any way to achieve this? Or maybe another way to achieve the UserControl assigning a unique GroupName to the RadioButtons without seting any other properties? I know I could set them manually, or create another property and use that, but I would like to know if this is possible or not.
To summarize, my goal is to have a UserControl with two RadioButtons, which automatically get their GroupName assigned to their parent YesNoSelection Name.
Upvotes: 0
Views: 424
Reputation: 27
OK so based on Clemens' advice, I tried both overriding OnInitialized and using the Loaded event. Overriding OnInitialized yielded the same result, but the Loaded event did the trick. So the correct code in this case is
public YesNoSelection()
{
InitializeComponent();
this.Loaded += YesNoSelection_Loaded;
}
private void YesNoSelection_Loaded(object sender, RoutedEventArgs e)
{
rbnYes.GroupName = this.Name;
rbnNo.GroupName = this.Name;
}
Many thanks to Clemens for the solution!
Upvotes: 1