为什么找不到正确的标签(标签为空)?

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

我今天已经问过这个问题了,为什么我在这段代码中出现异常(查看)。现在我不再遇到异常,但它 returns 的标签为空(它不是 returns 标签)。如有其他问题,请随时提问。

如果我调试代码并打开 grid.children,我会得到以下路径:

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

我的代码:

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);
    };
}

您搜索名称为 "label" 的标签。

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

但是你创建后忘了命名