4

First of all, I'm newbie in WPF and specially in MVVM. I have a window with diferent tabs and a very large ViewModel with the business logic of the content of every tab. I know it is not right, so now I'm trying to do it more elegant:

As I see googling, an idea is to do a collection of a "base" viewmodel from wich inherit the sub-viewmodels of every tab, and a collection on this "base" viewmodel in the viewmodel of the window.

TabBaseViewModel
Tab1ViewModel inherits TabBaseViewModel
Tab2ViewModel inherits TabBaseViewModel

MainWindow ViewModel --> Collection of TabBaseViewModel

The contents the tabs do not have anything in common along each other.

How I have to proceed?

4

2 回答 2

3

如果您使用的是 MVVM ,则应该考虑使用 MVVM 框架。以Caliburn.Micro为例,您可以将主视图定义为:

<TabControl x:Name="Items">
    <TabControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding DisplayName}" />
        </DataTemplate>
    </TabControl.ItemTemplate>
</TabControl>

其中数据上下文是具有集合的导体类型。该Items属性将公开您的视图模型的集合:

public class MainViewModel : Conductor<IScreen>.Collection.OneActive
{ 
    private OneOfMyViewModels oneOfMyViewModels;

    private AnotherViewModel anotherViewModel;

    protected override void OnInitialise()
    {
        // Better to use constructor injection here
        this.oneOfMyViewModels = new OneOfMyViewModels();
        this.anotherViewModel = new AnotherViewModel();

        this.Items.Add(this.oneOfMyViewModels);
        this.Items.Add(this.anotherViewModel);
    }

    protected override void OnActivate()
    {
        base.OnActivate();
        this.ActivateItem(this.oneOfMyViewModels);
    }
}

public class OneOfMyViewModels : Screen
{
    public OneOfMyViewModels()
    {
        this.DisplayName = "My First Screen";
    }
}
于 2013-07-26T08:13:21.557 回答
0

我发布了一个不同问题的答案,该问题显示了如何做到这一点:如何获取对 ViewModel 的引用

这是一个非常简单的例子,但希望能让你走上正确的道路。

于 2013-07-26T10:24:38.867 回答