【发布时间】:2016-07-19 13:56:39
【问题描述】:
在使用 XAML 时,将 UserControl 放置在 TabItem 中是非常基本的。
<TabControl>
<TabItem>
<local:MyUserControl/>
</TabItem>
</TabControl>
但是假设我想使用 ViewModel 加载 UserControl。我该怎么做呢?比如
<TabControl ItemsSource="{Binding TabCollection}">
<TabItem Header="{Binding Header}"
Source="{Binding MyUserControl}"> <!-- Source is obviously not a property of TabItem-->
<!-- I'm just using it in this context as an example. Like how a 'Frame' would work -->
</TabItem>
</TabControl>
假设我的 ViewModel 有一个 ObservableCollection 用于填充不同的选项卡、标题、背景颜色等,我将如何以编程方式填充 TabItem 中的视图?
例如,下面是 ViewModel 的基本示例:
public class TabViewModel
{
// 'TabModel' is a simple class that acts as a Model for this class (TabViewModel)
// All it does is store strings, integers, etc. as properties
// i.e: the fields 'Header' and 'MyUserControl' in the below method are both strings declared in 'TabModel'
public ObservableCollection<TabModel> TabCollection { get; set; }
public TabViewModel()
{
TabCollection = new ObservableCollection<TabModel>();
PopulateTabCollection();
}
private void PopulateTabCollection()
{
TabCollection.Add(new TabModel()
{
Header = "FirstUserControl",
MyUserControl = "Views/MyFirstUserControl.xaml"
});
TabCollection.Add(new TabModel()
{
Header = "SecondUserControl",
MyUserControl = "Views/MySecondUserControl.xaml"
});
}
}
所以我需要做的是通过数据绑定在每个选项卡中显示不同的视图。我什至不确定这是否可能。但如果是的话,请教育我。
【问题讨论】: