为什么会出现System.InvalidOperationException? [英] Why do I get a System.InvalidOperationException?
问题描述
此刻我真的很绝望.我正在编写WPF程序.我建立了一个简单的XAML-construct
,并根据数据库中存储了多少个元素来动态生成网格并在网格标签内动态生成了网格.即使定义了Label并将其命名为Label,我仍然得到一个System.InvalidOperationException
.我在此处找到了该解决方案.我的实际问题是,我需要在此网格中获取标签的内容.我提出的问题都与我所链接的问题类似.
I'm really desperate at the moment. I'm programming a WPF-programm. I built a simple XAML-construct
and generated grids and within the grids labels dynamically, based on how many elements are stored in the database. Even though I defined the Label and named it label, I get an System.InvalidOperationException
. I found this solution here. My actual problem was, that I needed to get the content of the label in this grid. I made all similar to the question, which I linked.
希望您能理解我的意思.
I hope that you understand what I mean.
这是我的代码:
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;
upperGrid.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>().First(k => k.Name=="label"); //Here I get the exception
string result = lbl.Name.ToString();
Console.WriteLine(result);
};
}
推荐答案
首先会抛出.使用 FirstOrDefault
会返回default<T>
以及 null-条件运算符(?.
):
First will throw. Use FirstOrDefault
that will return the default<T>
and also null-conditional operator (?.
):
Label lbl = grid.Children.OfType<Label>().FirstOrDefault(k => k.Name=="label");
string result = lbl?.Name.ToString();
Console.WriteLine(result);
但是,由于这是一个WPF项目,因此我建议使用MessageBox
或类似的东西来显示结果,而不是Console.WriteLine
,如下所示:
However, Since this is a WPF project, I suggest use a MessageBox
or something similar to show the result, instead of Console.WriteLine
, like this:
首先将其添加到您的using
指令中:
Add this to your using
directives first:
using System.Windows;
然后:
MessageBox.Show(result);
这篇关于为什么会出现System.InvalidOperationException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!