WPF ComboBox SelectedItem not Updating

前端 未结 3 1097
無奈伤痛
無奈伤痛 2021-01-24 11:54

I am facing a problem while working with a WPF ComboBox. My situation is that I have a ComboBox that is displaying some values. I am adding ContentControls to Combo

3条回答
  •  情歌与酒
    2021-01-24 12:47

    I have resolved this issue with a different way.
    ComboBox SelectedItem is not what it displays but is what you select. When you select an Item comboBox takes the ComboBox displays it in SelectionBox's Template not in SelectedItem,s Template. If you will go into VisualTree of ComboBox, you will see that it has a ContentPresenter that contains a TextBlock and this TextBlock is assigned with the text of selected item.
    So what i did, in SelectionChanged event handler i looked for the TextBlock inside that ContentPresenter using VisualTreeHelper and then i Binded the Text property of this TextBlock to the Content property of my ContentControl(SelectedItem).

    Edit:

    In the SelectionChanged evetn handler of ComboBox I wrote:

    ModifyCombox(cmbAnimationBlocks, myComboBox.SelectedItem.As());
    

    and this method is:

        private static void ModifyCombox(DependencyObject comboBox, ContentControl obj)
        {
            if (VisualTreeHelper.GetChildrenCount(comboBox) > 0)
            {
                WalkThroughElement(comboBox, obj);
            }
        }
    
        private static void WalkThroughElement(DependencyObject element, ContentControl contentControl)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
            {
                if (element.GetType() == typeof(ContentPresenter))
                {
                    ContentPresenter contentPresenter = element.As();
                    TextBlock textBlock = VisualTreeHelper.GetChild(contentPresenter, 0).As();
                    textBlock.SetBinding(TextBlock.TextProperty, new Binding("Content")
                    {
                        Source = contentControl
                    });
                    contentPresenter.Content = textBlock;
                }
                else
                {
                    DependencyObject child = VisualTreeHelper.GetChild(element, i).As();
                    WalkThroughElement(child, contentControl);
                }
            }
    
            if (VisualTreeHelper.GetChildrenCount(element) == 0 && element.GetType() == typeof(ContentPresenter))
            {
                ContentPresenter contentPresenter = element.As();
                TextBlock textBlock = new TextBlock();
                textBlock.SetBinding(TextBlock.TextProperty, new Binding("Content")
                {
                    Source = contentControl
                });
                contentPresenter.Content = textBlock;
            }
        }
    

提交回复
热议问题