1
<Button Name="B1">
    <Grid>
        <Label/>
        <Label/>
    </Grid>
</Button>
<Button Name="B2">
    <Grid>
        <Label/>
        <Label/>
    </Grid>
</Button>
<Button Name="B3">
    <Grid>
        <Label/>
        <Label/>
    </Grid>
</Button>

How can I access B2 Label 2 without using a name attribute. Something like that:

B2.Children[0].Children[1].Content = "Thank You <3"
ynsbl.eng
  • 142
  • 2
  • 8
  • 1
    `((Label)((Grid)B2.Content).Children[1]).Content = "Like this";` It would however make more sense to create a DataTemplate for a specific view model type that holds the Grid with the two Labels, where the Label's Content is bound to properties of the view model class. Then assign an instance of that class to the Content property of the Button. – Clemens Sep 28 '20 at 05:05
  • You save me a lot of time, thank you very much! for the object conversion I use an extension so your code be like: B2.Content.Root().Children[0].Root – ynsbl.eng Sep 28 '20 at 05:31
  • That doesn't make any sense to me. It is a static method that performs an explicit cast - as a replacement for directly writing that cast. Totally pointless, sorry. Consider using the DataTemplate approach. That would make sense. – Clemens Sep 28 '20 at 05:40
  • Why do you want to avoid the name or x:Name attribute? – StayOnTarget Sep 28 '20 at 13:20
  • @UuDdLrLrSs suppose I want to change the background of the first label when a button is clicked, I can do something like: `Container.Children.OfType – ynsbl.eng Sep 28 '20 at 17:33

1 Answers1

1

You can use trigger to change the label background according to clicking to Button like below:

  <Style TargetType="Label" x:Key="MyLable">
        <Style.Triggers>
            <DataTrigger Binding="{Binding Path=IsPressed,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Button}}}"  Value="true">
                <Setter Property="Background" Value="Blue" ></Setter>
            </DataTrigger>
        </Style.Triggers>
    </Style>
DasiyTian_1203
  • 1,038
  • 1
  • 6
  • 16
  • Thanks for your reply, according to the documentation: triggers will reset to the initial state once the condition is no longer satisfied. What I want to achive is to change the background color permantly after the button click. That's why I'm creating this in the code behind. – ynsbl.eng Sep 29 '20 at 17:46
  • 2
    @ynsbl.eng, you can get children elements by type, for more information, please refer to:https://stackoverflow.com/questions/10279092/how-to-get-children-of-a-wpf-container-by-type – Zhanglong Wu - MSFT Sep 30 '20 at 09:50