且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从一个窗口移动用户控件WPF到另一个?

更新时间:2023-10-11 13:49:46

是的,你可以通过删除用户控件主窗口做到这一点,将其添加为一个逻辑孩子任何的控制在 PopupWin 窗口。

Yes you can do this by removing the userControl from the Mainwindow and adding it as a logical child to any of the control in the PopupWin window.

如何从一个窗口移动用户控件WPF到另一个?

UserControl.xaml:

UserControl.xaml:

<UserControl x:Class="WpfApplication1.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" 
             mc:Ignorable="d" 
             d:DesignHeight="100" d:DesignWidth="100">
    <Grid>
        <TextBox x:Name="txtBlock1" Text="hai"/>
    </Grid>
</UserControl>

MainWindow.xaml:

MainWindow.xaml :

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:WpfApplication1="clr-namespace:WpfApplication1" Title="MainWindow" Height="550" Width="555">
    <Grid>
        <StackPanel x:Name="mainPanel" Orientation="Vertical ">
            <Button Content="Button" Height="23" Name="button1" Width="75" Click="button1_Click" />
            <WpfApplication1:UserControl1 x:Name="myUserControl" />
        </StackPanel>
    </Grid>
</Window>

PopupWin.xaml:

PopupWin.xaml :

<Window x:Class="WpfApplication1.PopupWin"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="PopupWin" Height="300" Width="300">

    <StackPanel x:Name="mainPanel"/>

</Window>

PopupWin.xaml.cs:的揭露一个新的构造接受用户控件并将其添加为一个孩子的的mainPanel

PopupWin.xaml.cs: Expose a new constructor to accept userControl and add it as a child to the mainPanel

public partial class PopupWin : Window
{
    public PopupWin()
    {
        InitializeComponent();
    }

    private UserControl control;

    public PopupWin(UserControl control)
        : this()
    {
        this.control = control;

        this.mainPanel.Children.Add(this.control);
    }
}

MainWindow.xaml.cs 的在Button_Click从目前的主窗口删除用户控件,并把它传递给 PopupWin ,在这种情况下,通过构造。

MainWindow.xaml.cs On Button_Click remove the userControl from the current MainWindow and pass it to PopupWin, in this case via constructor.

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        this.mainPanel.Children.Remove(this.myUserControl);

        var wind = new PopupWin(this.myUserControl);

        wind.ShowDialog();
    }

注意:的在用户控件实例应该永远只有有一个元素的逻辑子在任何时候。

Note: The userControl instance should always be a logical child of only one element at anytime.