Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Finding the wrong UIElement in Grid

Problem: When I select a check box (in Column ‘1’), the OnSelection event should find a Label on Column ‘0’ in the same Row, but I am getting:

System.InvalidCastException: ‘Unable to cast object of type ‘System.Windows.Controls.CheckBox’ to type ‘System.Windows.Controls.Label’.’

I am initializing the view as such:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Label lbName = new() { Content = "labelName" };
Grid.SetColumn(lbName, 0);
GrWindow.Children.Add(lbName);

CheckBox ckSelection = new();
ckSelection.Checked += OnSelection;
Grid.SetColumn(ckSelection, 1);
GrWindow.Children.Add(ckSelection);

And on the OnSelection method, where the exception is triggered:

string? labelName = GrWindow.Children.
                     Cast<Label>().
                     First(e => Grid.GetRow(e) == row && Grid.GetColumn(e) == 0).
                     Content as string;

In other place in my app, I am using a very similar approach to get a name from Row ‘0’ and works fine.

There is only one children on every row/column = ‘0’, and its a label, I dont know how to debug such situations, since the checkbox is on column=’1′.

Thanks in advance.

>Solution :

Replace

.Cast<Label>()

with

.OfType<Label>()

to get only the Labels.

Otherwise you are trying to cast all child elements to Label, which will of course fail for the CheckBox.


An alternative to querying the Children collection might be to assign the associated Label to the Tag property of the CheckBox

ckSelection.Tag = lblName;

and get it back in the event handler by

var checkBox = (CheckBox)sender;
val label = (Label)checkBox.Tag;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading