简体   繁体   中英

Does Grid.Children.Clear() really remove all controls?

Edit:
Simple answer: Yes, it does. I found the error, which was, that another event handler was added, everytime the Combobox_SelectionChanged was fired. Hence, the collection looked fine, but the Items_CollectionChanged was fired multiple times. Once this was fixed, everything worked fine.
End Edit.

I've got a page with a combobox and a grid. The grid fills dynamically, when the selection in the combobox changes. I'm now observing a strange thing. When I select a value for the second time in the combobox, the childitems in the grid appear twice. I've checked the underlying collections, which look fine (ie only one record per item). When I jump out of the combobox_SelectionChanged method, after the Grid.Children.Clear() command, the screen looks fine, ie empty.

My guess is, that Grid.Children.Clear() only removes the controls from the visual tree, but the actual controls are still hanging around. Any Ideas?

private void combobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    grItems.Children.Clear();
    grItemsColumnDefinitions.Clear();
    grItemsColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(200) });
}

    private void Items_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {

        if (e.Action == NotifyCollectionChangedAction.Add)
        {
             grItems.Children.Add(new ChildItemControl(e.NewItems[0]));
        }

    } 

Edit: The whole thing is supposed to look like this (fictional - but hopefully understandable - example) 在此处输入图片说明

I would suggest you use the built in Databinding for WPF. You could use something like this:

<DataGrid x:Name="grItems" ItemsSource="{Binding comboboxItems}" />

Then, when you update comboboxItems your grid will automatically update too!
Here is a great article on Databinding with the DataGrid control: http://www.wpftutorial.net/DataGrid.html

For more information about Databinding in general, here is a good article: https://msdn.microsoft.com/en-us/library/aa480224.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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