Search code examples
c#wpfxamlstackpanel

StackPanel.Children.Clear() does not work correctly


I have a problem when I delete the children of my StackPanel.

At the start my StackPanel is empty. I call a method to add 11 TextBox in it. I want to delete the 11 TextBox before call this method again. So I call my stackpanel :

myStackPanel.Children.Clear()

and it is working (try with debug point and count). There are no children in StackPanel but the method returns 22 TextBox after the second call.

What is wrong with that please ?

XAML :

<StackPanel x:Name="myStackPanel"/>

WPF :

var count1 = myStackPanel.Children.Count; // 11 (first call give me 11)
myStackPanel.Children.Clear();
var count2 = myStackPanel.Children.Count; // 0 (it is working)
using (var selectAll = new Database1Entities())
{
    var querySelectAll =
        from myVariable
        in selectAll.Entrees
        select myVariable;
    foreach (var ligne in querySelectAll) // 11 (0 + 11 = 11 right ?)
    {
        TextBox myTextBoxNom = new TextBox();
        myTextBoxNom.Text = ligne.Nom;
        myStackPanel.Children.Add(myTextBoxNom);
    }
}
var count3 = myStackPanel.Children.Count; // EDIT >> 11 (but 22 on screen)

EDIT :: Works with tip in comment


Solution

  • I never found a solution for this bug however I used the DataBinding to avoid it like you can read in the comments.