将 UIElement 转换为对象?

Convert a UIElement to an Object?

在这个问题中,我如何将 UIElement 转换为 CartesianChart (LiveCharts)。

在此代码中,我检查 CartesianChart 的网格,然后我 想要 存储它(在 ch 中)。

            CartesianChart ch;

            for (int i = 0; i < Grid.Children.Count; i++)
            {
                var temp = Grid.Children[i].GetType();
                if (temp.Name == "CartesianChart")
                {
                    ch = Grid.Children[i];
                }
            }
            ch.Name = "Chart";
            ch.Margin = new Thickness(0, 0, 250, 125);
            ch.Series = new SeriesCollection

它说 are you missing a cast?,但我不确定如何将 UIElement 转换为 Object

您可以使用as operator

 ch = Grid.Children[i] as CartesianChart;

cast operator

ch = (CartesianChart)Grid.Children[i];

解释了它们之间的主要区别here

我建议使用第一种方法。它看起来像

 CartesianChart ch = null; // this lets avoid a compiler warning about using uninitialized vars
 for (int i = 0; i < Grid.Children.Count; i++)
 {
    ch = Grid.Children[i] as CartesianChart;
    if (ch != null)
    {
       break;
    }
 }
 if (ch != null)
 {
     ch.Name = "Chart";
     ch.Margin = new Thickness(0, 0, 250, 125);
     ch.Series = new SeriesCollection ...
 }

请注意,此代码将在网格中找到第一个 CartesianChart(如果可以有多个,则应执行额外检查)。

您还可以使用 Linq 遍历网格的子项,过滤请求的类型并选择第一个:

CartesianChart ch = Grid.Children.OfType<CartesianChart>().FirstOrDefault();

老实说,您的代码遍历了网格的所有子项并将每个 CartesianChart 分配给您的变量。所以在它完成 for 循环后,找到的最后一个匹配元素存储在变量中。
如果这是您想要的行为,请使用此代码:

CartesianChart ch = Grid.Children.OfType<CartesianChart>().LastOrDefault();