WPF TabControl,内容控制项绑定

本文关键字:控制项 绑定 TabControl WPF | 更新日期: 2023-09-27 18:29:38

我正在尝试将"内容控制项"控件绑定到选项卡项标题,但不起作用,如何正确绑定。

我想在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; }
        }
    }

WPF TabControl,内容控制项绑定

我们的想法是将Header绑定到集合,然后只将textblock绑定到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>

将Count绑定到Window而不是ContentControl的相对源更改为您想要的,假设这是在WPF窗口中。如果是UserControl,请将其更改为等。您可能也想在"项目计数"后面加一个空格。。。

<TextBlock Text="{Binding Items.Count, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}"/>