基本上我的 MainViewModel.cs 中有:
ObservableCollection<TabItem> MyTabs { get; private set; }
但是,我需要以某种方式不仅能够创建选项卡,还需要加载选项卡内容并将其链接到适当的 View 模型,同时维护 MVVM。
基本上,我如何才能将用户控件作为 tabitem 的内容加载,并将该用户控件连接到适当的 View 模型。使这变得困难的部分是 ViewModel 不应该构造实际的 View 项,对吧?或者可以吗?
基本上,这是否适合 MVVM:
UserControl address = new AddressControl();
NotificationObject vm = new AddressViewModel();
address.DataContext = vm;
MyTabs[0] = new TabItem()
{
Content = address;
}
我之所以这么问,是因为我正在从 ViewModel 中构建一个 View (AddressControl),这对我来说听起来像是 MVVM 禁忌。
最佳答案
这不是 MVVM。您不应该在 View 模型中创建 UI 元素。
您应该将选项卡的 ItemsSource 绑定(bind)到 ObservableCollection,并且该模型应该包含有关应创建的选项卡信息的模型。
以下是代表选项卡页的虚拟机和模型:
public sealed class ViewModel
{
public ObservableCollection<TabItem> Tabs {get;set;}
public ViewModel()
{
Tabs = new ObservableCollection<TabItem>();
Tabs.Add(new TabItem { Header = "One", Content = "One's content" });
Tabs.Add(new TabItem { Header = "Two", Content = "Two's content" });
}
}
public sealed class TabItem
{
public string Header { get; set; }
public string Content { get; set; }
}
这是绑定(bind)在窗口中的外观:
<Window x:Class="WpfApplication12.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<ViewModel
xmlns="clr-namespace:WpfApplication12" />
</Window.DataContext>
<TabControl
ItemsSource="{Binding Tabs}">
<TabControl.ItemTemplate>
<!-- this is the header template-->
<DataTemplate>
<TextBlock
Text="{Binding Header}" />
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<!-- this is the body of the TabItem template-->
<DataTemplate>
<TextBlock
Text="{Binding Content}" />
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
</Window>
(请注意,如果您希望在不同的选项卡中显示不同的内容,请使用 DataTemplates
。每个选项卡的 View 模型应该是其自己的类,或者创建自定义的 DataTemplateSelector
> 选择正确的模板。)
数据模板内的用户控件:
<TabControl
ItemsSource="{Binding Tabs}">
<TabControl.ItemTemplate>
<!-- this is the header template-->
<DataTemplate>
<TextBlock
Text="{Binding Header}" />
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<!-- this is the body of the TabItem template-->
<DataTemplate>
<MyUserControl xmlns="clr-namespace:WpfApplication12" />
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
关于c# - 如何将 TabControl 绑定(bind)到 ViewModel 集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5650812/