簡體   English   中英

讓Unity在XAML中解析視圖

[英]Getting Unity to Resolve views in XAML

我開始使用MVVM,我開始理解它。 我目前正在嘗試使用Cinch框架,盡管我還沒有做到這一點。
我通過在視圖的代碼隱藏中引用ViewModel,將ViewModel注入到Views中,其中屬性具有[Dependency],並且在setter中使用Unity將DataContext設置為右視圖。 我想,整潔的把戲。

我正在嘗試讓我的應用程序作為單個窗口工作,注入視圖(與多個窗口相反並處理打開\\關閉它們)我將視圖從Windows更改為UserControls,並將a添加到主窗口。 這很有效,但ViewModel從未被注入,大概是因為XAML不使用Container.Resolve來創建視圖,就像我創建視圖並使用Resolve在代碼隱藏中手動添加它一樣,創建了[Dependency] 。

我如何設置我的窗口,以便如果我通過XAML添加視圖,或者視圖因UI動作等而改變,它會通過Unity獲取它,以便它可以發揮其魔力?

通常使用Regions和RegionManager解決此問題。 在主窗口ViewModel中,創建一組區域並將其添加到RegionManager。 然后可以解析ViewModels並將其添加到Region.Views集合中。

在XAML中,通常通過將ItemsControl的ItemsSource屬性綁定到主ViewModel的region屬性來注入Region。

所以,在主屏幕ViewModel中你會得到這樣的東西:

    public class TestScreenViewModel
{
    public const string MainRegionKey = "TestScreenViewModel.MainRegion";

    public TestScreenViewModel(IUnityContainer container, IRegionManager regionManager)
    {
        this.MainRegion = new Region();
        regionManager.Regions.Add(MainRegionKey, this.MainRegion);
    }

    public Region MainRegion { get; set; }
}

這將在您的IModule中正常解決

        #region IModule Members

    public void Initialize()
    {
        RegisterViewsAndServices();

        var vm = Container.Resolve<SelectorViewModel>();
        var mainScreen = Container.Resolve<TestScreenViewModel>();
        mainScreen.MainRegion.Add(vm);

        var mainView = ContentManager.AddContentView("Test harness", mainScreen);
    }

    #endregion

並且模板的XAML表示看起來像

    <DataTemplate DataType="{x:Type TestModule:TestScreenViewModel}">
    <ScrollViewer ScrollViewer.VerticalScrollBarVisibility="Auto">
        <StackPanel>
            <ItemsControl ItemsSource="{Binding Path=MainRegion.Views}" />
        </StackPanel>
    </ScrollViewer>
</DataTemplate>

解決問題的方法是使窗口也具有ViewModel,並將UserControls的ViewModel作為屬性公開。 然后在您的XAML窗口中,您只需使用綁定機制將UserControl的DataContexts綁定到您的主ViewModel的正確屬性。 由於主要的ViewModel是從Unity容器中解析出來的,因此可以根據需要注入所有其他ViewModel。

暫無
暫無

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

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