【问题标题】:Why it doesn't find the correct label (label is null)?为什么找不到正确的标签(标签为空)?
【发布时间】:2018-05-29 13:46:30
【问题描述】:

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

如果我调试代码并打开 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);
    };
}

【问题讨论】:

    标签: c# .net wpf lync


    【解决方案1】:

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

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

    但是你创建后忘记命名了

    【讨论】:

    • 天啊,我不敢相信我这么愚蠢。我一直在寻找故障,大约两个小时......非常感谢!我想, .Name 是我在创建它的实例时给标签的名称。你知道吗,如果你知道我的意思,我怎么能在标签中搜索它的变量名。
    • 这是不可能的,因为可能有很多(也有零个)变量指向特定标签
    • 要以变量名命名,可以使用label.Name = nameof(label)
    猜你喜欢
    • 1970-01-01
    • 2011-12-16
    • 1970-01-01
    • 1970-01-01
    • 2021-01-09
    • 2018-10-08
    • 2017-08-03
    • 1970-01-01
    • 2021-06-30
    相关资源
    最近更新 更多