当前位置:  开发笔记 > 编程语言 > 正文

MVVM:查看导航无法正常工作

如何解决《MVVM:查看导航无法正常工作》经验,为你挑选了0个好方法。

我使用Brian Noyes的Pluralsight课程,"WPF MVVM In Depth"作为我的主要来源,他所展示的作品非常出色.

但是,我没有根据在UtilitiesView上单击的按钮切换视图,而是希望根据工具栏按钮(构成VS 2015扩展包的一部分)切换视图,用户可以在其中选择特定实例.

UtilitiesView是由包扩展打开的窗口上的用户控件.所以这是UtilitiesView中的xaml:`


    
        
    
    
        
    



    
        
                                 
    
    
        
            
            
            
        
        

可以看出,有两个按钮通过绑定到ChangeViewModelCommand并传递字符串值("CalculationEngine"或"TAEngine")来切换View.

这是UtilitiesViewModel.cs类:

 public class UtilitiesViewModel : BindableBase
{
    #region Fields

    public RelayCommand ChangeViewModelCommand { get; private set; }

    private CalcEngineViewModel calcViewModel = new CalcEngineViewModel();
    private TAEngineViewModel taViewModel = new TAEngineViewModel(); 

    private BindableBase currentEngineViewModel;

    public BindableBase CurrentEngineViewModel
    {
        get { return currentEngineViewModel; }
        set
        {
            SetProperty(ref currentEngineViewModel, value);
        }
    }


    #endregion

    public UtilitiesViewModel()
    {          
        ChangeViewModelCommand = new RelayCommand(ChangeViewModel);      
    }



    #region Methods

    public void ChangeViewModel(string viewToShow) //(IEngineViewModel viewModel)
    {
        switch (viewToShow)
        {
            case "CalculationEngine":
                CurrentEngineViewModel = calcViewModel;
                break;
            case "TAEngine":
                CurrentEngineViewModel = taViewModel;
                break;
            default: 
                CurrentEngineViewModel = calcViewModel;
                break;
        }            
    }

    #endregion
}

这是BindableBase.cs:

public class BindableBase : INotifyPropertyChanged
{
    protected virtual void SetProperty(ref T member, T val, [CallerMemberName] string propertyName = null)
    {
        if (object.Equals(member, val)) return;

        member = val;
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    public event PropertyChangedEventHandler PropertyChanged = delegate { };
    protected virtual void OnPropertyChanged(string propertyName)
    {         
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));     
    }
}

我使用一个简单的ViewModelLocator类来链接Views和它们的ViewModel:

 public static class ViewModelLocator
{
    public static bool GetAutoWireViewModel(DependencyObject obj)
    {
        return (bool)obj.GetValue(AutoWireViewModelProperty);
    }

    public static void SetAutoWireViewModel(DependencyObject obj, bool value)
    {
        obj.SetValue(AutoWireViewModelProperty, value);
    }

    // Using a DependencyProperty as the backing store for AutoWireViewModel.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty AutoWireViewModelProperty =
        DependencyProperty.RegisterAttached("AutoWireViewModel", typeof(bool), typeof(ViewModelLocator), new PropertyMetadata(false, AutoWireViewModelChanged));

    private static void AutoWireViewModelChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (DesignerProperties.GetIsInDesignMode(d)) return;
        var viewType = d.GetType();
        var viewTypeName = viewType.FullName;
        var viewModelTypeName = viewTypeName + "Model";
        var viewModelType = Type.GetType(viewModelTypeName);
        var viewModel = Activator.CreateInstance(viewModelType);
        ((FrameworkElement)d).DataContext = viewModel;
    }
}

如前所述,使用UtilitiesView.xaml上定义的按钮切换视图可以正常工作.

工具栏按钮从Package.cs类中调用UtilitiesViewModel.cs中的上述ChangeViewModel方法,但即使CurrentEngineViewModel属性设置不同,它也不会反映在UtilitiesView.xaml上.

当我调试时,然后在两种情况下它都正确地进入BindableBase的SetProperty,但是在ToolBar按钮的情况下,从不调用ViewModelLocator中的AutoWireViewModelChanged方法.

我不知道为什么不.我原本认为UtilitiesView中的绑定与UtilitiesViewModel的属性CurrentEngineViewModel就够了吗?我试着把它想象成我在模型组件中做了一些改变,而View应该对此作出反应,即使我实际上有工具栏按钮作为人们认为视图组件的一部分.

这是在Package.cs类中调用ChangeViewModel方法的方法:

if (Config.Engine.AssemblyPath.Contains("Engines.TimeAndAttendance.dll"))
                {
                    uvm.ChangeViewModel("TAEngine");
                }
                else //Assume Calculation Engine
                {
                    uvm.ChangeViewModel("CalculationEngine"); 
                }

我希望我已经给出了足够的细节.

更新1

关于gRex的评论,我想也许有两个UtilitiesViewModel对象.

这是打开包扩展的自定义窗口时发生的情况:

public class SymCalculationUtilitiesWindow : ToolWindowPane
{
    /// 
    /// Initializes a new instance of the  class.
    /// 
    public SymCalculationUtilitiesWindow() : base(null)
    {
        this.Caption = "Sym Calculation Utilities";

        this.ToolBar = new CommandID(new Guid(Guids.guidConnectCommandPackageCmdSet), Guids.SymToolbar);
        // This is the user control hosted by the tool window; Note that, even if this class implements IDisposable,
        // we are not calling Dispose on this object. This is because ToolWindowPane calls Dispose on
        // the object returned by the Content property.
        this.Content = new UtilitiesView();

    }

}

调用AutoWireViewModelChanged方法将UtilitiesViewModel链接到内容的UtilitiesView.

在Package.cs类中,我有这个字段:

 private UtilitiesViewModel uvm;

在Initialize方法中我有:

 uvm = new UtilitiesViewModel();

uvm对象用作原始帖子中的代码片段(刚好在UPDATE之上),以使用适当的字符串参数调用ChangeViewModel方法.

这会给我两个不同的对象,不是吗?如果是这样,并假设这可能是问题的根本原因,我怎样才能改善这一点,我必须使UtilitiesViewModel成为单身人士吗?

更新2

我已经为Github添加了一个解决方案.功能略有改变,因此我不需要与原始解决方案的其余部分进行任何交互.因此,"连接"按钮(在工具栏上)使用"TAEngine"参数调用ChangeViewModel方法,"保存"按钮(在工具栏上)执行相同操作,但使用"CalculationEngine"作为参数.目前DataTemplates仍然被注释掉,所以只能在文本中看到类名.这是链接.在Visual Studio的实验实例中,可以在View - > Other Windows - > SymplexityCalculationUtilitiesWindow中找到该窗口.如果您还没有Visual Studio SDK,则可能需要下载它.

更新3

我使用带有ContainerControlledLifetimeManager的Unity IoC容器来确保我没有两个不同的UtilitiesViewModel.实现此功能后,工具栏按钮可以导航正确的视图.

推荐阅读
和谐啄木鸟
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有