【问题标题】:Set a usercontrol as content to another window's content at run time在运行时将用户控件设置为另一个窗口的内容
【发布时间】:2013-02-20 01:33:35
【问题描述】:

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

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

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();
        }
      }
    }

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

【问题讨论】:

  • 从未使用过 WPF,所以我不发布这个答案,但内容是读/写的。您能否简单地说:this.Content = null; 在分配给 tempFullScreenWindow 之前?
  • Steve 这段代码在用户控件本身内部,这就是为什么我使用 ownerWindow = Window.GetWindow(this); 来查找托管窗口的原因。而且我不能使内容为空,因为父窗口可能包含其他可能丢失的用户控件。
  • 好吧,在这种情况下,您可以将您的用户控件设置为一个面板,其中它是唯一的孩子。然后设置 panel.content = null 应该是无害的。出于好奇,我发现this thread 正在讨论类似的问题。希望对你有帮助

标签: c# wpf user-controls fullscreen


【解决方案1】:

使用

mywindow.Content = new MyuserControl();

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

【讨论】:

  • 数据我试图找到如何将用户控件的实例从 OwnerWindow 与用户控件的代码分离
  • 创建了一个新的用户控件实例并将数据上下文复制到新实例并将新控件显示为新全屏窗口的子项。
【解决方案2】:

为什么这么复杂?

您只需要将当前主机窗体切换到全屏模式。

public void GoToFullScreen()
{
  this.FormBorderStyle = FormBorderStyle.None;
  this.WindowSate = FormWindowState.Maximized;
}

【讨论】:

  • 我在当前主机中有两个面板,我只想最大化托管用户控件的右侧面板。我也只有在用户控件中有最大化按钮。我还想在许多其他对话框中重复使用此控件。
  • 因此您不需要移动控件,只需在另一个表单上创建另一个实例并将所有需要的数据发送到该控件实例即可。
猜你喜欢
  • 1970-01-01
  • 2021-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-11
  • 1970-01-01
  • 1970-01-01
  • 2012-12-16
相关资源
最近更新 更多