簡體   English   中英

將派生的ViewModel映射到Caliburn.Micro中的基類View

[英]Mapping derived ViewModels to base class View in Caliburn.Micro

我有一個基本的ViewModel和相關的View。 我還從基礎ViewModel中獲得了多個派生的ViewModel,但我想使用基本View進行顯示。

基本ViewModel和View:

  • vm: MyCompany.MyApp.Modules.Wizard.ViewModels.WizardViewModel
  • vw: MyCompany.MyApp.Modules.Wizard.Views.WizardView

源自WizardViewModel

  • vm: MyCompany.MyApp.Modules.NewSpec.ViewModels.NewSpecViewModel : WizardViewModel
  • vw :(映射到MyCompany.MyApp.Modules.Wizard.Views.WizardView

  • vm: MyCompany.MyApp.Modules.NewSpec.ViewModels.NewMaterialViewModel : WizardViewModel

  • vw :(映射到MyCompany.MyApp.Modules.Wizard.Views.WizardView

我認為這應該可以使用ViewLocator或ViewModelLocatorNameTransformer中的映射,但我還沒有想到它。

我正在使用Gemini FrameworkCaliburn.Micro v1.5.2(我打算很快升級到v2)。

這是我嘗試過的一件事:

public class NewSpecViewModel : WizardViewModel
{
    // ...
    static NewSpecViewModel()
    {
        // Escape the '.' for the regular expression
        string nsSource = typeof(NewSpecViewModel).FullName.Replace(".", @"\.");
        string nsTarget = typeof(WizardViewModel).FullName;
        nsTarget = nsTarget.Replace("WizardViewModel", "Wizard");
        // nsSource = "MyCompany\\.MyApp\\.Modules\\.NewSpec\\.ViewModels\\.NewSpecViewModel"
        // nsTarget = "MyCompany.MyApp.Modules.Wizard.ViewModels.Wizard"
        ViewLocator.AddTypeMapping(nsSource, null, nsTarget);
    }
    // ...
}

PS我知道有現有的向導框架( 擴展的WPF工具包Avalon向導等),但我不想添加另一個第三方程序集,並且擴展的WPF工具包向導無法正常工作。

PPS我也想在其他地方使用這種基本的ViewModel / View映射方式。

這是[鏈接]( https://caliburnmicro.codeplex.com/discussions/398456 )以正確的方式執行此操作。

編輯:由於codeplex正在關閉,以下是討論中的代碼:

var defaultLocator = ViewLocator.LocateTypeForModelType;
ViewLocator.LocateTypeForModelType = (modelType, displayLocation, context) =>
{
    var viewType = defaultLocator(modelType, displayLocation, context);
    while (viewType == null && modelType != typeof(object))
    {
        modelType = modelType.BaseType;
        viewType = defaultLocator(modelType, displayLocation, context);
    }
    return viewType;
};

我知道它已經晚了...但是可以選擇將ViewModel直接綁定到視圖,這可能對其他人有幫助。

我還會將此綁定附加到基類構造函數。 以下適用於我:

public abstract class WizardViewModel {
    protected WizardViewModel() {
        // this --> points the child class
        ViewModelBinder.Bind(this, new WizardView(), null);
    }
}

有了這個,現在每個孩子都使用WizardView (在子類中沒有任何額外的編程)。

public class NewSpecViewModel : WizardViewModel {}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM