Cris
Cris

Reputation: 12204

WPF: weird problem in dataBinding with TabControl

I'm trying to use DataBinding for dynamically populating a TabControl but have a problem. dataBinding runs fine but I would like the content of each TabItem to be independent one from the other. Here is my XAML code:

<TabControl
    DockPanel.Dock="Left"
    ItemsSource="{Binding OpenChats}"
    Name="tabChats"
    VerticalAlignment="Top"
    Width="571">

    <TabControl.ItemTemplate>
        <DataTemplate>
            <TextBlock
                Text="{Binding Name}" />
        </DataTemplate>
    </TabControl.ItemTemplate>
    <TabControl.ContentTemplate>
        <DataTemplate>

            <TextBox />
        </DataTemplate>
    </TabControl.ContentTemplate>

</TabControl>

TabItems are created with different headers (as I want) but when the user types something in the TextBox inside the ContentTemplate, the same text is maintained in different tabItems and I don't want this.

What am I doing wrong?

Upvotes: 1

Views: 1157

Answers (2)

askorvaga
askorvaga

Reputation: 81

I had same problem. This answer helped me. My solution was to remove focus from textbox when tab changed. When focus from textbox is removed, new content is set to binded property as expected.

private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        DependencyObject focusedElement = (FocusManager.GetFocusedElement(tabControl) as DependencyObject);
        if (focusedElement != null)
        {
            DependencyObject ancestor = VisualTreeHelper.GetParent(focusedElement);
            while (ancestor != null)
            {
                var element = ancestor as UIElement;
                if (element != null && element.Focusable)
                {
                    element.Focus();
                    break;
                }

                ancestor = VisualTreeHelper.GetParent(ancestor);
            }
        }

    }

or use

Text="{Binding UpdateSourceTrigger=PropertyChanged}"

on textbox binding.

Upvotes: 1

J&#246;rg Reichardt
J&#246;rg Reichardt

Reputation: 361

The TextBox in the ContentTemplate has no Binding. Try

<TabControl.ContentTemplate>
    <DataTemplate>
        <TextBox Text="{Binding}" />
    </DataTemplate>
</TabControl.ContentTemplate>

Adjust the bindingpath if necessary

Upvotes: 0

Related Questions