Search code examples
c#wpf

Access content in XAML from code behind without name


I'm new to C# and XAML, so please excuse any obvious mistakes.

Let's say I wanted to create 100 checkboxes, all with the same layout, and when you click the checkbox, it makes the text in a label that's a child to that checkbox turn bold. I don't want to write out 100 functions for 100 checkboxes, I want to make a single function each checkbox can call that'll do the same thing.

<CheckBox VerticalContentAlignment="Center" Checked="CheckBox_Checked">
    <WrapPanel>
        <Image> Width="50" Source="Images/example.jpg"/>
        <Label VerticalContentAlignment="Center">Extra cheese</Label>
    </WrapPanel>
</CheckBox>

I'm able to get the WrapPanel nested under the CheckBox, but I can't seem to do the same to get the Label which is nested in the WrapPanel.

private void CheckBox_Checked(object sender, RoutedEventArgs e)
    {
        CheckBox _cb = (CheckBox)sender;
        WrapPanel _wp = (WrapPanel)(_cb).Content;
        Label _lb = (Label)(_wp).Content;
        _lb.FontWeight = FontWeights.Bold;
    }

Solution

  • The wrap panel class doesn't have a content attribute. What you can use however is the Children attribute in a combination with FirstOrDefault OfType. the method could look somethind like this.

    private void CheckBox_Checked(object sender, RoutedEventArgs e)
    {
       CheckBox _cb = (CheckBox)sender;
       WrapPanel _wp = (WrapPanel)(_cb).Content;
       Label lbl = _wp.Children.OfType<Label>().FirstOrDefault();
       lbl.FontWeight = FontWeights.Bold;
    }