0

I am trying to locate a label by its tag so i can add an additional label beside when a certain condition is met.

in old school winform i would just use:

Label sublabel = Controls.Find(Sub.id, true).FirstOrDefault() as Label;

snippet of the view.xaml:

<Grid>
    <Label 
        Content = "{Binding Path = NodeName, Mode = OneWay}" 
        Background = "{Binding Path = NodeStatus, Mode = OneWay}"
        Tag="{Binding Path = Nodeid, Mode = OneWay}"

i have tried something along these lines:

var label = Grid.Children.OfType<Label>()
    .First(i => i.Tag == "tagid");

but generates

An object reference is required for the non-static field, method, or property 'Panel.Children'

Thanks for looking

mm8
  • 163,881
  • 10
  • 57
  • 88
Dwayne Dibbley
  • 355
  • 3
  • 20
  • Maybe this can help you: https://stackoverflow.com/questions/636383/how-can-i-find-wpf-controls-by-name-or-type – Malior Mar 18 '19 at 14:09
  • In MVVM you shouldn't be manipulating the view like that. Seems like you should be setting a flag, or updating a string in the VM that causes the view to do what you want – BradleyDotNET Mar 18 '19 at 14:11
  • This may help: https://stackoverflow.com/a/44138544/177416 – Alex Mar 18 '19 at 14:17

1 Answers1

5

You could give the Grid an x:Name in your XAML markup:

<Grid x:Name="theGrid">

...and refer to it by this name in your code:

var label = theGrid.Children.OfType<Label>() ...

Note that this is not MVVM by any means though. Using MVVM, you would access the Nodeid source property rather than the Tag property of the Label element.

mm8
  • 163,881
  • 10
  • 57
  • 88