WPF:使用TabControl进行dataBinding中的怪异问题 [英] WPF: weird problem in dataBinding with TabControl
问题描述
我正在尝试使用DataBinding动态填充TabControl,但是有问题. dataBinding
运行正常,但我希望每个TabItem的内容彼此独立.这是我的XAML代码:
< TabControlDockPanel.Dock =左"ItemsSource ="{Binding OpenChats}"名称="tabChats"VerticalAlignment =顶部"宽度="571".< TabControl.ItemTemplate>< DataTemplate>< TextBlock文字="{{绑定名称}""/></DataTemplate></TabControl.ItemTemplate>< TabControl.ContentTemplate>< DataTemplate>< TextBox/></DataTemplate></TabControl.ContentTemplate></TabControl>
TabItems是使用不同的标题创建的(根据我的需要),但是当用户在ContentTemplate内部的TextBox中键入内容时,相同的文本将保存在不同的tabItems中,我不希望这样做.
我在做什么错了?
我遇到了同样的问题.这个 answer 帮助了我.我的解决方案是在选项卡更改时从文本框中删除焦点.删除文本框的焦点后,新内容将按预期设置为绑定属性.
private void TabControl_SelectionChanged(对象发送者,SelectionChangedEventArgs e){DependencyObjectfocusedElement =(FocusManager.GetFocusedElement(tabControl)作为DependencyObject);如果(focusedElement!= null){DependencyObject祖先= VisualTreeHelper.GetParent(focusedElement);while(祖先!= null){var element =祖先作为UIElement;if(element!= null&&&元素.Focusable){element.Focus();休息;}祖先= VisualTreeHelper.GetParent(祖先);}}}
或使用
Text ="{Binding UpdateSourceTrigger = PropertyChanged}"
关于文本框绑定.
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?
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.
这篇关于WPF:使用TabControl进行dataBinding中的怪异问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!