gpt4 book ai didi

c# - 如何将 WPF UserControl 从一个窗口移动到另一个窗口?

转载 作者:太空狗 更新时间:2023-10-30 00:25:43 25 4
gpt4 key购买 nike

假设我在 MainWindow.xaml 中有一个名为 MyVideoControl 的用户控件:

<Window Name="_mainWindow">
<Grid>
<MyVideoControl Name="_localVideo"/>
</Grid>
</Window>

现在用户单击一个按钮,我希望 UserControl float 在 MainWindow.xaml 之上,在一个新创建的名为 PopUp.xaml 的窗口中。

<Window Name="_popUpWindow">
<Grid>
<MyVideoControl Name="_localVideo"/>
</Grid>
</Window>

我如何完成此操作,以便移动整个对象?目前我使用 XAML 以声明方式将 MyVideoControl 放置在我的窗口中,但我猜我需要以编程方式完成所有操作?

最佳答案

是的,您可以通过从 Mainwindow 中删除 userControl 并将其作为逻辑子项添加到 PopupWin 中的任何控件来实现> 窗口。

enter image description here

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>

主窗口.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:

<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: 公开一个新构造函数以接受 userControl 并将其作为子项添加到 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 上从当前 MainWindow 移除 userControl 并将其传递给 PopupWin ,在本例中是通过构造函数。

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

var wind = new PopupWin(this.myUserControl);

wind.ShowDialog();
}

注意:userControl 实例在任何时候都应该始终只是一个 元素的逻辑子元素。

关于c# - 如何将 WPF UserControl 从一个窗口移动到另一个窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15891869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com