【问题标题】:Bring to front previously opened UserControl将先前打开的 UserControl 置于前面
【发布时间】:2017-06-13 02:39:24
【问题描述】:

我正在开发具有一个父窗口和多个子用户控件的 WPF 应用程序。这是我的父窗口 xaml:

<DockPanel>
    <Menu DockPanel.Dock="Top">
        <MenuItem Header="STUDENT INFORMATION">
            <MenuItem Header="ADD" Cursor="Hand" Click="MenuItem_Click"></MenuItem>
            <Separator></Separator>
            <MenuItem Header="EDIT" Name="mnuEdit" Cursor="Hand" Click="mnuEdit_Click"></MenuItem>
        </MenuItem>            
    </Menu>

    <ContentControl x:Name="childWindow" Margin="10"></ContentControl>
</DockPanel>

这是我打开子窗体的 C# 代码:

        childWindow.Content = new ctrStudentAdd();

一切正常。但是当我点击添加菜单项时,我怎么能:

  1. 检查选定的用户控件之前是否已经打开?
  2. 如果它已打开,只需将其放在前面而不是打开新实例?

提前致谢。

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    您可以使用 is 运算符来确定 Content 属性当前是否设置为 ctrStudentAdd

    if(childWindow.Content is ctrStudentAdd)
    {
        //...
    }
    

    我注意到你所说的“带到前面”是什么意思。将 ContentControl 的 Content 属性设置为另一个 UC 后,对前一个 UC 的引用就消失了,并且“旧”UC 有资格进行垃圾收集,除非有其他对象持有对它的引用。

    如果您不想每次在 ContentControl 中显示 UserControl 时都创建一个新实例,您可以在窗口类中保留对它的引用,例如:

    public partial class MainWindow : Window
    {
        private readonly ctrStudentAdd _ctrStudentAdd = new ctrStudentAdd();
        private readonly ctrStudentEdit _ctrStudentEdit = new ctrStudentEdit();
    
        public MainWindow()
        {
            InitializeComponent();
        }
    
        private void Switch()
        {
            childWindow.Content = _ctrStudentAdd;
            ...
            childWindow.Content = _ctrStudentEdit;
        }
    }
    

    【讨论】:

    • 在 WinForms 中打开多个子窗体时,可以调用 Application.OpenForms['MyFormName"].BringToFront() 将特定的活动窗体置于最前面
    • 所以你想把父 window 放在前面?然后 yoy 应该调用它的 Activate() 方法:stackoverflow.com/questions/257587/…
    • 如您所见,我有两个菜单项 (UserControls) 添加和编辑。当我打开添加然后编辑并再次添加时,我想将之前打开的添加用户控件放在前面。用户控件没有 Activate() 方法。
    • 没错。并且没有办法将 UserControl 放在前面。将 ContentControl 的 Content 属性设置为另一个 UC 后,对前一个 UC 的引用就消失了,并且有资格进行垃圾收集,除非有其他对象持有对它的引用。
    • 您建议使用什么代替 UserCotrol 作为 MainWindow 的子表单,这样我就可以实现我的目标?所以当我打开一个新的孩子时,之前打开的只是隐藏而不是删除。
    猜你喜欢
    • 2012-10-07
    • 1970-01-01
    • 2012-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多