Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
When I click the button for the first time, usercontrol1 opens but when I click the second button, usercontrol2 does not open(usercontrol2 opens but form1 doesn't hide so form2 can't be seen). Both Form1 and Form2 are to be opened in the same panel

What I have tried:

C#
userControl1.Visibility = Visibility.Collapsed;
userControl2.Visibility = Visibility.Visible;

UserControl1 newFormControl = new UserControl1();
settingpanel.Children.Add(newFormControl);
Posted
Updated 6-Feb-23 22:13pm
v2
Comments
Graeme_Grant 7-Feb-23 3:45am    
MVVM or code-behind?

1 solution

Here is a code-behind version:

1. UI/XAML
XML
<Window x:Class="WpfControlHost.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="450" Width="800" >

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <ContentControl x:Name="ContentControl" />
        <Button Grid.Row="1"
                HorizontalAlignment = "Center"
                VerticalAlignment = "Center"
                Padding="20 10"
                Margin="10"
                Content="SWAP"
                Click="ButtonBase_OnClick"/>
    </Grid>
</Window>

2. Code-behind:
C#
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        SwapControls();
    }

    private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
    {
        SwapControls();
    }

    private void SwapControls()
    {
        ContentControl.Content = ContentControl.Content?.GetType()
            == typeof(UserControl1)
            ? new UserControl2()
            : new UserControl1();
    }
}
 
Share this answer
 
Comments
Maciej Los 7-Feb-23 11:57am    
5ed!
Graeme_Grant 7-Feb-23 16:59pm    
ty
Maciej Los 9-Feb-23 11:47am    
Do you know that in polish language "ty" means "you"? :)
Graeme_Grant 9-Feb-23 17:48pm    
Oh ... nice to know

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900