每次激活父对话框时,又显示一次子对话框

时间:2019-01-25 08:37:09

标签: c# wpf mvvm

我开发了一个应用程序,用户从列表中按顺序分组。如果选择了订单,则显示EditOrderWindow。在此窗口中,用户可以将项目添加到“订购依据”。这是在子对话框AddItemWindow中完成的。一阶效果很好。

但是,如果编辑了第二个订单,则AddItemWindow将在关闭后再次显示。对于编辑的三阶,它显示三倍的aso。

我不知道为什么会发生这种情况,以及如何防止这种情况发生。

ViewModel

public class ViewModel
{
    public ICommand EditOrderCommand { get; set; }
    public ICommand AddItemCommand { get; set; }

    public event EventHandler<int> EditOrder;
    public event EventHandler<int> AddItem;
    public event EventHandler<int> ItemAdded;

    public ViewModel()
    {
        //Is fired when an item in the datagrid in Control OrderList is doubleclicked
        EditOrderCommand = new ICommand();
        EditOrderCommand.Executed += EditOrderCommand_Executed();

        //Is fired when the users click on add in EditOrderWindow
        AddItemCommand = new ICommand();
        AddItemCommand.Executed += AddItemCommand_Executed();
    }

    private void EditOrderCommand_Executed(object sender, EventArgs e)
    {
        if (SelectedOrder != null)
        {
            EditOrder(this, SelectedOrder.Id);
        }            
    }

    private void AddItemCommand_Executed(object sender, EventArgs e)
    {
        AddItem(this, new EventArgs());
    }

}

控件:OrderList

public partial class OrderList : UserControl
{
    ViewModel vm;

    public OrderList()
    {
        InitializeComponent();

        //DataContext is set in xmal
        vm = (ViewModel)this.DataContext;

        vm.EditOrder += Vm_EditOrder;
    }       

    private void Vm_EditOrder(object sender, int e)
    {
        EditOrderWindow s = new EditOrderWindow(vm);          
        s.ShowDialog();
        s = null;
    }

窗口:EditOrderWindow

public partial class EditOrderWindow : Window
{
    ViewModel vm;
    AddItemWindow aiw;

    public EditOrderWindow(ViewModel _vm)
    {

        InitializeComponent();

        vm = _vm;
        this.DataContext = vm;

        vm.AddItem -= Vm_AddItem;
        vm.AddItem += Vm_AddItem;

    }

    private void Vm_AddItem(object sender, EventArgs e)
    {
        if (aiw == null)
        {
            aiw = new AddItemWindow(vm);
        }

        aiw.ShowDialog();
        aiw = null;
    }
}

Window:AddItemWindow

public partial class AddItemWindow : Window
{
    public AddItemWindow(ViewModel _vm)
    {
        InitializeComponent();

        this.DataContext = _vm;

        _vm.ItemAdded -= _vm_ItemAdded;
        _vm.ItemAdded += _vm_ItemAdded;

    }

    private void _vm_ItemAdded(object sender, EventArgs e)
    {

        this.Close();

    }   
}

0 个答案:

没有答案