Here is how did. Assuming the UserControl to be added is defined in the Resources of Grid.
<grid name="grid">
<grid.resources>
<local:ausercontrol x:key="myUserControl" xmlns:x="#unknown" xmlns:local="#unknown" />
</grid.resources>
<RadioButton Margin="28,29,0,0" Name="radioButton1" Height="16" HorizontalAlignment="Left" VerticalAlignment="Top" Width="120">RadioButton</RadioButton>
<StackPanel Margin="28,81,26,28" Name="stackPanel1"/>
<RadioButton Height="16" HorizontalAlignment="Right" Margin="0,29,38,0" Name="radioButton2" VerticalAlignment="Top" Width="120">RadioButton</RadioButton>
</grid>
And in my code-behind, I did this :
public class Window1
UserControl uc;
public Window1()
{
InitializeComponent();
radioButton1.Checked += new RoutedEventHandler(radioButton1_Checked);
radioButton1.Unchecked += new RoutedEventHandler(radioButton1_Unchecked);
}
void radioButton1_Unchecked(object sender, RoutedEventArgs e)
{
stackPanel1.Children.Remove(uc);
}
void radioButton1_Checked(object sender, RoutedEventArgs e)
{
uc = (UserControl)grid.FindResource("myUserControl");
stackPanel1.Children.Add(uc);
}
}
I have added another radiobutton(radiobutton2) so that the unchecked event can be handled for radiobutton1.
Did this work for you?