【问题标题】:WPF: Popout existing usercontrolWPF:弹出现有的用户控件
【发布时间】:2015-04-22 23:13:09
【问题描述】:

想象下一种情况:我确实有一个应用程序窗口,里面有几个用户控件。它们过去并排显示,但现在我想在弹出窗口中显示其中一个。不在 Popup 控件中,而是在新窗口中。

查看示例 XAML:

<Window x:Class="WpfApplication3.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:wpfApplication3="clr-namespace:WpfApplication3"
    Title="MainWindow"
    Height="350"
    Width="525">
<Grid>
    <wpfApplication3:UserControl1 Visibility="Hidden"
                                  x:Name="UserControl1"/>
    <Button Click="ButtonBase_OnClick"
            Width="100"
            Height="60">open window</Button>
</Grid>

在后面的代码中,我需要从当前窗口中分离用户控件并分配给新窗口:

  private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
    {
        var parent = VisualTreeHelper.GetParent(UserControl1);
        if (parent != null)
        {
            parent.RemoveChild(UserControl1);
        }

        var w = new Window
        {
            Content = UserControl1,
            Title = "sample",
            SizeToContent = SizeToContent.WidthAndHeight,
            ResizeMode = ResizeMode.CanResize

        };
        w.Show();
    }

在调用 w.Show() 之后,我总是得到空白的白色窗口。

如果在按钮单击处理程序中发生变化

内容 = UserControl1

内容 = new UserControl1()

我也会得到正确的内容。 但我不能使用这种方式,因为我想在弹出和弹出事件期间保持我的用户控件状态。 那么如何在新窗口中显示现有的用户控件而不重新创建它呢?

【问题讨论】:

    标签: c# wpf xaml user-controls


    【解决方案1】:

    我不确定您如何在 DependencyObject 上调用 RemoveChild,因为该方法似乎不存在。请注意,VisualTreeHelper.GetParent 返回一个 DependencyObject,因此,您发布的代码不应编译,除非您在某处定义了 RemoveChild 的扩展方法。

    在您的情况下,您想要做的是将您的父对象转换为类型 Grid 或 Panel,然后从 Children 属性中删除 UserControl,然后将您的 UserControl 设置为窗口的内容。

    private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
    {
        Grid parent = VisualTreeHelper.GetParent(UserControl1) as Grid;
        if (parent != null)
        {
            parent.Children.Remove(UserControl1);
        }
    
        var w = new Window
        {
            Content = UserControl1,
            Title = "sample",
            SizeToContent = SizeToContent.WidthAndHeight,
            ResizeMode = ResizeMode.CanResize
    
        };
        w.Show();
    }
    

    【讨论】:

      【解决方案2】:

      有人问过类似的问题here 这给出了一个非常详细的答案。

      快速回答是,您必须从主窗口中删除控件,然后将其添加到弹出窗口中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-15
        • 2023-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-18
        • 1970-01-01
        相关资源
        最近更新 更多