如何解决视图未关闭.Close()?

时间:2015-12-18 14:48:39

标签: c# wpf dialog

为了打开ProductView,我添加了一个DialogService,到目前为止,ShowDetailDialog()正在按预期工作。

问题:

我在ProductView上调用Close(),视图未关闭。我通过在对话框服务关闭方法的调用上设置断点来调试此问题。

当我逐步完成代码时,null检查显示productView为null,这会阻止调用Close()

有谁知道为什么productView为null? (虽然它在视图中显示数据)

DialogService:(托管显示和关闭方法)

namespace MongoDBApp.Services
{
    class DialogService : IDialogService
    {

        Window productView = null;
        ProductView _productView;

        public DialogService()
        {
            _productView = new ProductView();
        }

        public void CloseDetailDialog()
        {

            if (productView != null)
                productView.Close(); 
        }

        public void ShowDetailDialog()
        {
            _productView.ShowDialog();
        }
    }
}

ProductViewModel:(ProductVM摘要,在SaveCommand上调用close方法)

        private void SaveProduct(object product)
        {
            _dialogService.CloseDetailDialog();
            Messenger.Default.Send<ProductModel>(SelectedProduct);
        }

CustomerOrdersViewmodel:(最初调用ShowDetailDialog()的地方)

        private void EditOrder(object obj)
        {
            Messenger.Default.Send<ProductModel>(SelectedProduct);
            _dialogService.ShowDetailDialog();                         
        }

1 个答案:

答案 0 :(得分:1)

这就是我一直关闭窗户的方式。

这是我的命令:

class CancelCommand : ICommand
    {
        private NewTruckViewModel newTruck;
        public CancelCommand(NewTruckViewModel vm)
        {
            newTruck = vm;
        }
        public event EventHandler CanExecuteChanged;

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public void Execute(object parameter)
        {
            newTruck.Cancel();
        }
    }

这是我的视图模型和从我的命令调用的方法:

 private NewTruck myWnd; //View Declaration

//Ctor where I set myView (myWnd) equal to a view that is passed in.
public NewTruckViewModel(ObservableCollection<Truck> Trucks, NewTruck wnd, bool inEditTruck)
        {
            myEngine.stopHeartBeatTimer();
            editTruck = inEditTruck;
            myWnd = wnd;
            SaveTruckCommand = new SaveTruckCommand(this);
            CancelCommand = new CancelCommand(this);
            ClearCommand = new ClearCommand(this);
            SetLevel1MTCommand = new SetLevel1MTCommand(this);
            SetLevel2MTCommand = new SetLevel2MTCommand(this);
            SetLevel3MTCommand = new SetLevel3MTCommand(this);
            SetLevel1FLCommand = new SetLevel1FLCommand(this);
            SetLevel2FLCommand = new SetLevel2FLCommand(this);
            SetLevel3FLCommand = new SetLevel3FLCommand(this);
            myTrucks = Trucks;
        }
     public void Cancel()
            {
                myWnd.Close();
            }

这适合我。