-1

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.

Ethirix
  • 13
  • 7

2 Answers2

1

You can also use Linq to traverse through the children of your grid, filter the requested type and choose the first one:

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

To be honest, your code traverses through all the children of your grid and assigns every CartesianChart to your variable. So after it finishes with the for loop, the last matching element found is stored in the variable.
If this is your desired behaviour, use this code:

CartesianChart ch = Grid.Children.OfType<CartesianChart>().LastOrDefault();
Mike
  • 1,225
  • 10
  • 21
  • 1
    @Ethirix And this should of course be the accepted answer. – Clemens Apr 01 '20 at 19:43
  • @Clemens The other does what I asked, this is just an extra fix. On the side: I forgot (at the time) about handling if nothing was found. – Ethirix Apr 01 '20 at 19:54
  • @Ethirix - `FirstOrDefault()` and `LastOrDefault()` return null (default value) if the preceding `IEnumerable` is empty. So you simply wrap your following code in `if (ch != null) { ... }`. And if you want to perform the same actions for all `CartesianChart` elements, use LINQ's `.ForEach()` in the loop instead of `FirstOrDefault()` – Mike Apr 02 '20 at 07:36
  • @Mike Thanks for that note. – Ethirix Apr 02 '20 at 14:20
-1

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

Miamy
  • 2,162
  • 3
  • 15
  • 32