如何解决TabControl WPF中的TabControl
我正在尝试创建水平标签,以使用WPF动态加载垂直标签,如下所示。我想创建类似的内容,这不是我的应用程序的屏幕截图。
似乎我无法在选项卡项中创建选项卡控件。
我的XAML文件包含以下代码,试图在标签内容内添加TabControl
:
<Grid Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2">
<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>
<TabControl ItemsSource="{Binding steps}">
<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>
<TextBlock Text="{Binding Content}" />
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
</Grid>
我的C#代码包含以下对象:
public ObservableCollection<TabItem> Tabs { get; set; }
public AddElement()
{
Steps step = new Steps();
step.display = "1";
Steps step2 = new Steps();
step.display = "2";
ObservableCollection<Steps> stepsList = new ObservableCollection<Steps>();
stepsList.Add(step);
stepsList.Add(step2);
Tabs = new ObservableCollection<TabItem>();
Tabs.Add(new TabItem { Header = "One",Content = "One's content",Steps = stepsList });
Tabs.Add(new TabItem { Header = "Two",Content = "Two's content" });
}
public sealed class TabItem
{
public string Header { get; set; }
public string Content { get; set; }
public ObservableCollection<Steps> Steps { get; set; }
}
public class Steps
{
public string display { get; set; }
}
解决方法
您的代码中存在多个问题,需要对其进行修复以使其按预期工作。
-
Steps
属性的绑定中有错字。它必须以大写字母开头。<TabControl ItemsSource="{Binding Steps}">
-
从XAML中删除最后一个,或将其放入
Grid
中,如下所示。照原样,代码将无法编译,因为您只能将单个元素设置为DataTemplate
中的内容。<DataTemplate> <Grid> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <TabControl Grid.Row="0" ItemsSource="{Binding steps}"> <!-- ...other code. --> </TabControl> <TextBlock Grid.Row="1" Text="{Binding Content}" /> </Grid> </DataTemplate>
-
您已绑定到XAML中
Header
项的Content
和Steps
属性。此类型不具有任何这些属性,只有display
。您可以引入这些属性并删除display
。public class Steps { public string Header { get; set; } public string Content { get; set; } }
-
在
AddElement
中,您仅修改step
实例,而不修改step2
,因此它将为空。初始化两者,例如具有上述其他属性。Steps step = new Steps(); step.Header = "Header 1"; step.Content = "Content 1"; Steps step2 = new Steps(); step2.Header = "Header 2"; step2.Content = "Content 2";
-
如果要使内部
TabControl
的标签栏垂直显示在左侧,则必须相应地设置TabStripPlacement
属性。<TabControl ItemsSource="{Binding Steps}" TabStripPlacement="Left">
使用默认的WPF样式,结果看起来像这样。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。