WPF: weird problem in dataBinding with TabControl

此生再无相见时 提交于 2019-12-14 02:27:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!