WPF:使用 MVVM 模式执行 Tabcontrol 的正确方法

标签 wpf mvvm viewmodel tabcontrol

首先,我是 WPF 的新手,特别是 MVVM。我有一个带有不同选项卡的窗口和一个非常大的 ViewModel,其中包含每个选项卡内容的业务逻辑。我知道这是不对的,所以现在我试图做得更优雅:

正如我看到的谷歌搜索,一个想法是做一个“基本” View 模型的集合,从它继承每个选项卡的 subview 模型,以及窗口 View 模型中这个“基本” View 模型的集合。

TabBaseViewModel
Tab1ViewModel inherits TabBaseViewModel
Tab2ViewModel inherits TabBaseViewModel
MainWindow ViewModel --> CollectionTabBaseViewModel
选项卡的内容彼此没有任何共同点。

我必须如何进行?

最佳答案

你应该考虑 using an MVVM framework if you're using MVVM .与 Caliburn.Micro例如,您可以将主 View 定义为:

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

其中数据上下文是 Conductor具有集合的类型。 Items属性将公开您的 View 模型的集合:
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";
    }
}

关于WPF:使用 MVVM 模式执行 Tabcontrol 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17875170/

相关文章:

C# MVVM 如何从模型更新 View 模型字符串

asp.net-mvc - Dictionary<Enum, string>() 不会绑定(bind)到 mvc 中的模型

WPF:自定义控件属性已被另一个自定义控件错误注册

c# - 未定义的枚举 & WPF ComboBox & WCF 序列化

wpf - 无法获得附加的属性(property)值(value)

mvvm - Sencha Touch 能否很好地适应 KnockoutJS 之类的 MVVM 模式?

dependency-injection - 无法从组合函数创建 View 模型

c# - 在 WPF 中打开 WebView2 会在调用 EnsureCoreWebView2Async 时导致 System.UnauthorizedAccessException

c# - 为什么 ShowGridLines 这么慢?

.net - 为什么在MVVM Light中没有PropertyChanged的简写