显示背景较暗的模态形式的更好方法是什么?

时间:2019-02-22 00:30:32

标签: c# winforms

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关闭,您需要使用这两次来关闭两种形式
  

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

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

1 个答案:

答案 0 :(得分:1)

可能适用于您变暗的叠加形式和模式形式的修改:

  1. 修改叠加层的构造器,以便您可以传递“模态”对话框的实例。
  2. 使调用方形成覆盖所有者(带有[DimBackground].Show(this);),以便覆盖可以使用所有者对象来适应其尺寸。
  3. 叠加层预订了收到的模态表单实例的FormClosed事件。
  4. 修改Modal Form的构造函数,以便它可以接受用于显示信息的类对象。
  5. 当模式窗体关闭时,如果引发其FormClosed事件,则覆盖图会自行关闭并激活调用者窗体。

添加所需的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
    }
}