且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WPF:使用TabControl进行dataBinding中的怪异问题

更新时间:2023-12-06 17:15:16

我遇到了同样的问题.这个 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.