gpt4 book ai didi

.net - 如何将不同的 tabItems 绑定(bind)到不同的 ViewModel

转载 作者:行者123 更新时间:2023-12-03 10:20:40 26 4
gpt4 key购买 nike

我不想把它全部放在一个 ViewModel 中,我希望每个 tabItem 有一个 viewModel。

我为包含 TabControl 的窗口创建了一个 mainViewModel,其中我有这个属性 currentViewModel,指向 mainViewModel 构造函数的默认值

    public MainViewModel()
{
currentViewModel = "viewModel1";
}

当用户单击另一个 tabItem 时,它会执行
currentViewModel = "viewModel2";

当然 set 访问器有 onPropertyChanged 方法
    public String currentViewModel
{
get { return _currentViewModel; }

set
{
_currentViewModel = value;
OnPropertyChanged("currentViewModel");
}
}

另外两个 View 模型(viewModel1,viewModel2)每个都决定了我想要在其中一个 tabItems 之间切换的功能。

现在在我的 Main.xaml 上,我想首先将我的 dataContext 绑定(bind)到 MainViewModel,然后再绑定(bind)到 currentViewModel 属性。这样,每当用户单击 tabItem 时,currentViewModel 属性就会更新,并且 dataContext 指向相应的 View 模型。

最佳答案

我认为一个好的方法是为每个选项卡项创建用户控件。然后,在每个用户控件中,您将引用要绑定(bind)到的正确 viewModel 命名空间。

您的 MainWindow 将具有 tabcontrol,并且 tabcontrol 内的每个 tabitem 都将绑定(bind)到特定的用户控件(被视为单独的 View )。

mainwindow_View.xaml 将绑定(bind)到 mainwindow_ViewModel.cs
tabItem1_View.xaml 将绑定(bind)到 ViewModel1.cs
tabItem2_View.xaml 将绑定(bind)到 ViewModel2.cs

如果您需要代码示例,请告诉我。

关于.net - 如何将不同的 tabItems 绑定(bind)到不同的 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5737476/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com