Search code examples
c#.netwpflync

Why it doesn't find the correct label (label is null)?


I already asked the question today, why I get an exception in this code (check it out here). Now I don't get an exception anymore, but the label it returns is null (it doesn't returns a label). For further questions, feel free to ask.

If I debug the code and I open grid.children I get the following path:

grid.children --> not open members (in German it says: "nicht öffentliche member") --> _visualChildren --> not open members --> _items --> _my label i want to get_

My code:

for (int i = 0; i < numberOfBooks; i++)
{
    Grid grid = new Grid();

    RowDefinition row = new RowDefinition();

    ColumnDefinition column = new ColumnDefinition();
    ColumnDefinition column2 = new ColumnDefinition();
    ColumnDefinition column3 = new ColumnDefinition();

    Label label = new Label();
    label.Content = Books[i].Titel;
    downGrid.RowDefinitions.Add(row);
    grid.ColumnDefinitions.Add(column);
    grid.ColumnDefinitions.Add(column2);
    grid.ColumnDefinitions.Add(column3);

    Grid.SetRow(label, i);
    Grid.SetColumn(label, 0);
    Grid.SetRow(grid, i);
    upperGrid.Children.Add(grid);
    grid.Children.Add(label);

    grid.MouseLeftButtonDown += (sen, evg) =>
    {
       Label lbl = grid.Children.OfType<Label>().FirstOrDefault(k => .Name=="label");
       string result = lbl?.Name;
       Console.WriteLine(result);
    };
}

Solution

  • You search labels for one with name "label".

    Label lbl = grid.Children.OfType<Label>().FirstOrDefault(k => .Name=="label");
    

    But you forgot to name it after you created it