问题
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 somwthing 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?
Thanks !
回答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.
回答2:
The TextBox in the ContentTemplate has no Binding. Try
<TabControl.ContentTemplate>
<DataTemplate>
<TextBox Text="{Binding}" />
</DataTemplate>
</TabControl.ContentTemplate>
Adjust the bindingpath if necessary
来源:https://stackoverflow.com/questions/6509264/wpf-weird-problem-in-databinding-with-tabcontrol