我正在尝试将Content Control Items控件绑定到Tab Item Header但不能正常工作,我该如何正确绑定。
我想在TabItem标题模板
中将Path = Items.Count绑定到Texblock<TabControl>
<TabItem>
<ContentPresenter Content="{Binding Items, Mode=OneTime}">
<ContentPresenter.ContentTemplate>
<DataTemplate>
<ListBox ItemsSource="{Binding}"/>
</DataTemplate>
</ContentPresenter.ContentTemplate>
</ContentPresenter>
<TabItem.HeaderTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Item Count"/>
<TextBlock Text="{Binding Path=Items.Count, RelativeSource={RelativeSource FindAncestor, AncestorType=ContentControl}}"/>
</StackPanel>
</DataTemplate>
</TabItem.HeaderTemplate>
</TabItem>
</TabControl>
代码背后
public partial class MainWindow : Window
{
private static ObservableCollection<string> items;
public MainWindow()
{
InitializeComponent();
DataContext = this;
items = new ObservableCollection<string>();
items.Add("test1");
items.Add("test2");
items.Add("test3");
items.Add("test4");
}
public static ObservableCollection<string> Items
{
get { return items; }
}
}
答案 0 :(得分:1)
我们的想法是将Header绑定到集合,然后将文本块绑定到count。
<TabControl>
<TabItem Header="{Binding Items}">
<ContentPresenter Content="{Binding Items, Mode=OneTime}">
<ContentPresenter.ContentTemplate>
<DataTemplate>
<ListBox ItemsSource="{Binding}" />
</DataTemplate>
</ContentPresenter.ContentTemplate>
</ContentPresenter>
<TabItem.HeaderTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Name="panel">
<TextBlock Text="Item Count"/>
<TextBlock Text="{Binding Count, StringFormat={} {0}}"/>
</StackPanel>
</DataTemplate>
</TabItem.HeaderTemplate>
</TabItem>
</TabControl>
答案 1 :(得分:0)
如果在WPF窗口中,则更改“计数到窗口”而不是“ContentControl”的绑定的相对源将执行您想要的操作。如果它是UserControl,将其更改为等等。您可能还希望在“项目计数”之后添加一个空格...
<TextBlock Text="{Binding Items.Count, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}"/>