Home > Enterprise >  Finding the wrong UIElement in Grid
Finding the wrong UIElement in Grid

Time:10-21

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:

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.

CodePudding user response:

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;
  • Related