c# - 在运行时将用户控件设置为另一个窗口的内容

标签 c# wpf user-controls fullscreen

我有一个带有用户控件的窗口。该用户控件有一个按钮,可将用户控件最大化至全屏。

为了实现此目的,我创建了一个临时窗口,将其缩放到当前屏幕边界并将其内容设置为用户控件。

private void OnBtnMaximizeClick(object sender, RoutedEventArgs e)
    {
      if (this.btnMaximize.IsChecked == true)
      {
        if (tempfullScreenWindow == null)
        {
          tempfullScreenWindow = new Window();
          tempfullScreenWindow.WindowStyle = WindowStyle.None;
          tempfullScreenWindow.ResizeMode = ResizeMode.NoResize;
        }
        var ownerWindow = Window.GetWindow(this);

        Screen screen = this.GetContainingScreen(ownerWindow);

        tempfullScreenWindow.Left = screen.WorkingArea.Left;
        tempfullScreenWindow.Top = screen.WorkingArea.Top;
        tempfullScreenWindow.Width = screen.Bounds.Width;
        tempfullScreenWindow.Height = screen.Bounds.Height;

        // InvalidOperationException comes here (Specified element is already the logical child of another element. Disconnect it first.)
        tempfullScreenWindow.Content = this;  

        tempfullScreenWindow.Owner = ownerWindow;
        tempfullScreenWindow.ShowDialog();
      }
      else
      {
        if (tempfullScreenWindow != null)
        {
          tempfullScreenWindow.Close();
        }
      }
    }

如何将用户控件设置为新创建的窗口的内容,方法是将其与所有者窗口分离,并在临时窗口关闭时将其重新附加到父窗口。

最佳答案

使用

mywindow.Content = new MyuserControl();

确保控件一次只能有一个父控件。首先从第一个窗口分离,然后将其附加到其他窗口。

关于c# - 在运行时将用户控件设置为另一个窗口的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10914610/

相关文章:

c# - 使用数据库部署 Visual Studio C# 项目

c# - Windows 手机 REST API

WPF:如何开始为使用 MVVM 构建的 DataGrid 设置样式?

c# - 以编程方式在 wpf : auto rowheight doesn't seem to work 中填充网格

c# - 我们为什么要使用用户控件?

c# - 将 byte[] 转换为文件流而不写入磁盘

c# - 将 .NetStandard 2.0 Nuget 包安装到 VS2015 Net 4.6.1 项目中

c# - 编写 XML 文件?

.net - WPF。 MVVM。使用事件是不好的口气吗?

c# - 从 WPF 中的一个 UserControl 中的 PropertyChanged 命令更新其他 ViewModel 和容器表单