在MVVM中捕获“切换工作空间”事件

时间:2012-06-27 15:17:07

标签: c# wpf mvvm

我有一个使用Josh Smith(http://msdn.microsoft.com/en-us/magazine/dd419663.aspx)的MVVM模式的应用程序构建。

当我在我的应用程序中打开多个工作区时,我想捕获切换工作区/选项卡的事件,以便我可以先保存当前工作区的内容。我查看了WorkspaceViewModel和ViewModelBase,但我不知道如何添加该EventHandler。

2 个答案:

答案 0 :(得分:1)

我在另一篇文章中找到了解决方案,我只需稍微调整一下:What is the proper way to handle multiple datagrids in a tab control so that cells leave edit mode when the tabs are changed?

基本上我在TabControl的PreviewMouseDown上添加了一个EventHandler,生成不同的工作区。

private void TabControl_PreviewMouseDown(object sender, MouseButtonEventArgs e) {
        MainWindow_VM dc = (MainWindow_VM)this.DataContext;

        if (IsUnderTabHeader(e.OriginalSource as DependencyObject))
            //Do what need to be done before switching workspace
            // in my case, switch the focus to a dummy control so the objectContext would save everything, even the currently focused textbox

    }

private bool IsUnderTabHeader(DependencyObject control) 
    {
        if (control is TabItem)
        {
            return true;
        }
        DependencyObject parent = VisualTreeHelper.GetParent(control); 
        if (parent == null)         
            return false; 

        return IsUnderTabHeader(parent); 
    }

答案 1 :(得分:0)

您应该能够将选项卡的“当前”项绑定到模型中的变量。当这种情况发生变化时,请做好工作。