我正在尝试动态加载标签项中的用户控件,但我无法这样做,我使用下面的代码。我也访问了各种帖子,但我有以下方式,请让我知道我错在哪里:< / p>
用户控制:
<UserControl x:Class="WpfApplication1.UserControl2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Button Content="welcome" Height="20" Width="70"></Button>
</Grid>
</UserControl>
视图模型:
namespace WpfApplication1
{
class Usercontrol2ViewModel
{
public ObservableCollection<TabItem> Tabs { get; set; }
public Usercontrol2ViewModel()
{
Tabs = new ObservableCollection<TabItem>();
//Tabs.Add(new TabItem { Header = "Overview", Content = new OverviewViewModel() }); How to load a usercontrol here if it's in the ItemCollection?
Tabs.Add(new TabItem { Header = "Overview", Content = new UserControl2() });
}
}
public class TabItem
{
public string Header { get; set; }
public object Content { get; set; } // object to allow all sort of items??
}
}
的MainPage:
<TabControl x:Name="MyTabControl"
ItemsSource="{Binding Tabs}">
<TabControl.Resources>
<DataTemplate DataType="{x:Type local:Usercontrol2ViewModel}">
<local:UserControl2></local:UserControl2>
</DataTemplate>
</TabControl.Resources>
<TabControl.ItemContainerStyle>
<Style TargetType="TabItem">
<Setter Property="Header" Value="{Binding Header}" />
</Style>
</TabControl.ItemContainerStyle>
</TabControl>
答案 0 :(得分:0)
我发现下面的问题是代码补丁的解决方案,需要在发布的代码上方正确
<Style TargetType="TabItem">
<Setter Property="Header" Value="{Binding Header}" />
<Setter Property="Content" Value="{Binding Content}"></Setter>
</Style>