简体   繁体   English

在TabItem中更改控件的值会使TabControl更改索引。 怎么样?

[英]Changing value of control in TabItem makes TabControl change index. How?

I have a TabControl in a WPF project that contains seven TabItems. 我在WPF项目中有一个TabControl,其中包含七个TabItem。
In one TabItem ( TabA ) I have a ComboBox bound to a list of items. 在一个TabItem( TabA )中,我有一个ComboBox绑定到项目列表。 The selected Item is bound to a property in my code-behind. 选定的项目绑定到我背后的代码中的属性。 This works fine, and I can change the property perfectly. 这很好,我可以完美地更改属性。
In another TabItem ( TabB ), I can change that same property in another way. 在另一个TabItem( TabB )中,我可以用另一种方式更改相同的属性。 The ComboBox will therefore relect the new value. 因此,组合框将选择新值。

The problem is that when the ComboBox in TabA changes it's SelectedItem due to the property changing from TabB - the OnSelectionChanged event somehow bubbles up to the TabControl, and raises the TabControlSelectionChanged event - even though nothing has happened with the tabs at all. 问题是,当在塔巴组合框改变它的SelectedItem由于物业从塔布改变-在OnSelectionChanged事件莫名其妙地冒泡到TabControl,并引发TabControlSelectionChanged事件-即使什么都没有用的标签发生在所有。

When I look at the arguments to the TabControlSelectionChanged event 当我查看TabControlSelectionChanged事件的参数时

var selectedTab = e.AddedItems[0] as TabItem;

selectedTab is null. selectedTab为空。

Why is this happening, and how do I prevent it occurring? 为什么会发生这种情况,如何防止这种情况发生?

Evil Str has answered the question, but after his lead, I found another method. Evil Str回答了这个问题,但是在他领导之后,我发现了另一种方法。
In the ComboBox SelectionChanged event, just prevent the event from bubbling further. 在ComboBox SelectionChanged事件中,只需防止该事件进一步冒泡。

private void ComboBoxOnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    // whatever code you want in here to handle the change of item
    e.Handled = true;
}

This is happening because the TabControl.SelectionChanged is the same event as a ComboBox.SelectionChanged. 发生这种情况是因为TabControl.SelectionChanged与ComboBox.SelectionChanged是同一事件。

I have already faced this problem once. 我已经遇到过这个问题了。 To prevent this from occurring, I used this code: 为了防止这种情况发生,我使用了以下代码:

private void myTab_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.Source is TabControl) //if this event fired from TabControl
            {
                if (tabItemName.IsSelected)
                {
                    //Do what you need here.
                }
            }
        }

You can adapt this code for what you need. 您可以根据需要修改此代码。 I hope this helps you. 我希望这可以帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM