ineffable p
ineffable p

Reputation: 1189

WPF TabControl , Content Control Items Binding

I am trying to bind Content Control Items control to Tab Item Header but not working, how can I bind rightly.

I want to bding Path=Items.Count to Texblock in TabItem Header Template

<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>

Code Behind

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; }
        }
    }

Upvotes: 0

Views: 1287

Answers (2)

TYY
TYY

Reputation: 2716

The idea is to bind the Header to the collection and then just bind the textblock to 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>

Upvotes: 1

Changing your relative source for the binding for the Count to Window instead of ContentControl will do what you want, assuming this is in a WPF window. If it's UserControl, change it to that etc. You probably want to put a space after "Item Count" as well...

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

Upvotes: 0

Related Questions