Search code examples
c#wpfcastinglivecharts

Convert a UIElement to an Object?


How would I go about converting a UIElement to a, in this problem, CartesianChart (LiveCharts).

In this code, I check for a Grid for a CartesianChart and then I want to store it (in 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

It says are you missing a cast?, but I'm unsure of how to cast a UIElement to an Object.


Solution

  • You can use as operator

     ch = Grid.Children[i] as CartesianChart;
    

    or cast operator

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

    The main difference between them is explained here

    I would recommend to use first approach. It can look like

     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 ...
     }
    

    Please take into account, this code will find a first CartesianChart in the grid (if you can have several ones, you should perform additional checks).