简体   繁体   中英

Show Usercontrol triggered from another Usercontrol WPF C#?

i have a WPF aplication in c# i have two usercontrol and the mainwindows, my first user control is usercontrol1 that hold my menu with one button and the event click, and i got a grid on my mainwindows name uscholder to load the usercontrol2 that i send from the event click of the button on my usercontrol1.

this my usercontrol1.cs

public  partial class UserControl1 : UserControl
    {
        public UserControl1()
        {
            InitializeComponent();

            
        }
       
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            UserControl2 usc = new UserControl2();
            MainWindow maingrid = new MainWindow();

            if (maingrid.uscholder != null)
            {
                maingrid.uscholder.Children.Clear();
                maingrid.uscholder.Children.Add(usc);
            }
            else
            {
                maingrid.uscholder.Children.Add(usc);
            }


        }
    }

this is my XAML

<Window x:Class="WpfApp5.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp5"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid >
        <local:UserControl1 HorizontalAlignment="Left" Width="262"></local:UserControl1>
        <Grid x:Name="uscholder" Margin="267,0,-0.4,0"/>

    </Grid>
</Window>

this is my usercontrol XAML

<UserControl x:Name="use1" x:Class="WpfApp5.UserControl1"
             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" 
             xmlns:local="clr-namespace:WpfApp5"
             mc:Ignorable="d" 
             d:DesignHeight="450" Width="226.303">
    <Grid Margin="0,0,0.4,-0.4">
        <Button Content="Button" HorizontalAlignment="Left" Margin="42,166,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>

    </Grid>
</UserControl>

On your main windows use "FindControl" function and search by UserControl name to access to the instance of each one of them. After that you can control directly each UserControl and perform selections or catch button clicks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM