1

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?

iknow
  • 8,358
  • 12
  • 41
  • 68
Cris
  • 12,124
  • 27
  • 92
  • 159

2 Answers2

1

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.

Community
  • 1
  • 1
askorvaga
  • 81
  • 3
0

The TextBox in the ContentTemplate has no Binding. Try

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

Adjust the bindingpath if necessary

Jörg Reichardt
  • 361
  • 5
  • 14
  • If i do this i see different values in TextBox but when i write a new value in textbox, change tab and return to original tab i lose what i've written. There must be something wrong :-( – Cris Jun 28 '11 at 20:02
  • Stick a debug breakpoint in the binding property... what happens? – Jake Berger Jun 28 '11 at 21:35
  • When you run the program, are there any Binding Expression Erorrs in the Output Window of Visual Studio? Maybe the Path is wrong. – Jörg Reichardt Jun 29 '11 at 08:25