Home > OS >  Access content in XAML from code behind without name
Access content in XAML from code behind without name

Time:12-19

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;
    }

CodePudding user response:

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;
}

CodePudding user response:

You can easily access the element you want without the need for hierarchical transformations that exist in HTML and there is no need for different transformations, so we will have the following code:

File.xml

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

File.cs

private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
    if (sender is CheckBox _cb)
    {
        if (_cb.FontWeight == FontWeights.Normal)
            _cb.FontWeight = FontWeights.Bold;
        else
            _cb.FontWeight = FontWeights.Normal;
        
    }
}
  • Related