亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

什么是ViewModelLocator?與DataTemplates相比,它的優缺點是什么?

什么是ViewModelLocator?與DataTemplates相比,它的優缺點是什么?

慕的地10843 2019-12-12 14:44:58
有人可以簡要概述一下ViewModelLocator是什么,它如何工作以及與DataTemplates相比使用它的優點/缺點嗎?我曾嘗試在Google上查找信息,但似乎有許多不同的實現方式,而沒有關于它的含義以及使用它的利弊的詳盡列表。
查看完整描述

3 回答

?
慕沐林林

TA貢獻2016條經驗 獲得超9個贊

我有一個視圖模型定位器類。每個屬性都將是我將在視圖上分配的視圖模型的實例。我可以檢查代碼是否在設計模式下運行或不使用DesignerProperties.GetIsInDesignMode。這使我可以在設計時使用模擬模型,并在運行應用程序時使用真實對象。


public class ViewModelLocator

{

    private DependencyObject dummy = new DependencyObject();


    public IMainViewModel MainViewModel

    {

        get

        {

            if (IsInDesignMode())

            {

                return new MockMainViewModel();

            }


            return MyIoC.Container.GetExportedValue<IMainViewModel>();

        }

    }


    // returns true if editing .xaml file in VS for example

    private bool IsInDesignMode()

    {

        return DesignerProperties.GetIsInDesignMode(dummy);

    }

}

要使用它,我可以將定位器添加到App.xaml資源中:


xmlns:core="clr-namespace:MyViewModelLocatorNamespace"


<Application.Resources>

    <core:ViewModelLocator x:Key="ViewModelLocator" />

</Application.Resources>

然后將您的視圖(例如:MainView.xaml)連接到您的視圖模型:


<Window ...

  DataContext="{Binding Path=MainViewModel, Source={StaticResource ViewModelLocator}}">


查看完整回答
反對 回復 2019-12-12
  • 3 回答
  • 0 關注
  • 1123 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號