显示具有暗淡背景的模态窗体的更好方法是什么?

问题描述 投票:1回答:1

enter image description here

正如您在上面的图像上看到的具有暗淡背景的模态形式,这就是我如何做到的。 我有两个表格,我同时打开它们。

private DimBackground dim;
private Modal modal;

private void ListEmployee_CellClick(object sender, DataGridViewCellEventArgs e)
{          
    if (e.RowIndex >= 0)
    {
        var row = employee.ListEmployee.Rows[e.RowIndex];
        Employee emp = new Employee().Get(row.Cells["Employee_ID"].Value.ToString());
        dim = new DimBackground();
        dim.Show();
        modal = new Modal(emp,dim);
        modal.ShowDialog();
    }     
}

对我来说,这不是一个好方法。这样做有问题

  • 当同时关闭这两个形式时,它会失去对主形的关注

为了解决这个问题,我关闭了模态窗体并隐藏了昏暗的窗体

  • Alt F4关闭,需要使用这两次关闭两种形式

当我试图禁用表单关闭时,表单被冻结

我怎样才能以更好/更清洁的方式实现这一目标?

c# winforms
1个回答
1
投票

可能的修改适用于您的灰色叠加和模态窗体:

  1. 修改Overlay的构造函数,以便传递Modal对话框的实例。
  2. 使调用者形成覆盖所有者(使用[DimBackground].Show(this);),因此覆盖可以使用所有者对象来适应其尺寸。
  3. Overlay订阅了它收到的模态表格实例的FormClosed事件。
  4. 修改模态窗体的构造函数,以便它可以接受用于显示信息的类对象。
  5. 当模态表格关闭时,如果提高其FormClosed事件,Overlay会自行关闭并激活调用者表单。

添加所需的null检查。


//Caller Form
private void ListEmployee_CellClick(object sender, DataGridViewCellEventArgs e)
{
    //(...)
    var row = employee.ListEmployee.Rows[e.RowIndex];
    Employee emp = new Employee().Get(row.Cells["Employee_ID"].Value.ToString());
    DimBackground overlay = new DimBackground(new Modal(emp));
    overlay.Show(employee);
}


public partial class DimBackground : Form
{
    Form frmDialog = null; 
    public DimBackground(Form dialog)
    {
        InitializeComponent();
        this.frmDialog = dialog;
        this.frmDialog.FormClosed += (obj, evt) => { this.Close(); };
    }

    private void DimBackground_Shown(object sender, EventArgs e) => this.frmDialog.ShowDialog();

    private void DimBackground_Load(object sender, EventArgs e)
    {
        if (this.Owner == null) return;
        this.Bounds = this.Owner.Bounds;
    }

    private void DimBackground_FormClosed(object sender, FormClosedEventArgs e)
    {
        this.Owner?.Activate();
    }
}

public partial class Modal : Form
{
    public Modal() : this(null) { }
    public Modal(Employee employee)
    {
        InitializeComponent();
        // Do something with the employee object
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.