如何 Wpf TabItem 样式 HeaderTemplate 绑定?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7498110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How To Wpf TabItem Style HeaderTemplate Binding?
提问by Ali Yousefi
How To do Wpf TabItem Style HeaderTemplate Binding?
如何进行 Wpf TabItem 样式 HeaderTemplate 绑定?
Code:
代码:
<TabControl x:Name="tabCtrlMain" ItemsSource="{Binding Items}" >
<TabControl.Resources>
<Style TargetType="TabItem">
<Setter Property="HeaderTemplate">
<Setter.Value>
<DataTemplate DataType="{x:Type TabItem}">
<TextBlock Text="{Binding FileName}"/>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</TabControl.Resources>
</TabControl>
this code is not working when binding:
绑定时此代码不起作用:
<TextBlock Text="{Binding FileName}"/>
回答by Akki922234
Try this Instead,
试试这个,
<TabControl x:Name="tabCtrlMain" ItemsSource="{Binding Items}" >
<TabControl.Resources>
<Style TargetType="TabItem">
<Setter Property="Header" Value="{Binding FileName}" />
<Setter Property="HeaderTemplate">
<Setter.Value>
<DataTemplate DataType="{x:Type TabItem}">
<Border x:Name="grid">
<ContentPresenter>
<ContentPresenter.Content>
<TextBlock Text="{TemplateBinding Content}"/>
</ContentPresenter.Content>
</ContentPresenter>
</Border>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</TabControl.Resources>
</TabControl>
回答by MojoFilter
I know this is awfully old now, but I thought I'd throw my two cents in just for the sake of completeness and historical accuracy :)
我知道这现在已经很老了,但我想我会为了完整性和历史准确性而投入我的两分钱:)
I prefer to use the ItemContainerStyle to do the same thing just because it feels a little cleaner to me because it states the purpose exactly:
我更喜欢使用 ItemContainerStyle 来做同样的事情,因为它对我来说感觉更简洁,因为它准确地说明了目的:
<TabControl ItemsSource="{Binding Items}">
<TabControl.ItemContainerStyle>
<Style TargetType="TabItem">
<Setter Property="Header" Value="{Binding FileName}" />
<Setter Property="HeaderTemplate">
<Setter.Value>
<DataTemplate>
<Border>
<TextBlock Text="{Binding Content}" />
</Border>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</TabControl.ItemContainerStyle>
</TabControl>
Also, if the only goal is to get the FileName into the tabs then it can be much simpler:
此外,如果唯一的目标是将 FileName 放入选项卡中,那么它可以简单得多:
<TabControl ItemsSource="{Binding Items}" DisplayMemberPath="FileName" />