Home > database >  Select Child Control of UserControl in XAML
Select Child Control of UserControl in XAML

Time:04-06

This is a general Syntax Question.

I have a UserControl

<UserControl x:Class="UserControlTest.Views.MyControl">
            
            <StackPanel Name="StackPanel1">
                <Button Name="Button1" Content="Hello From UserControl XAML"/>
                <Button Name="Button2" Content="Hello From UserControl XAML"/>
            </StackPanel>

</UserControl>

And the Window

<Window xmlns:views="using:UserControlTest.Views"
        x:Class="UserControlTest.Views.MainWindow">

    <views:MyControl Name="MyControl1"></views:MyControl>

</Window>

Is there a way to select the properties of the child elements from XAML of the MainWindow like i can do in cs?

So basically im looking for an XAML equivalent of this:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.Get<UserControl>("MyControl1").Get<Button>("Button1").Content = "Hello From Window CS";
    }
}

What i hope for is something similar to this:

<Window xmlns:views="using:UserControlTest.Views"
        x:Class="UserControlTest.Views.MainWindow">

    <views:MyControl Name="MyControl1">
        <views:MyControl ??? Button1> Hello From Window XAML <views:MyControl ??? Button1>
    </views:MyControl>
</Window>

This is only about selecting the child from outside in XAML. This is not about setting a value which can be achieved with bindings and a propper class definition.

CodePudding user response:

Not sure if this is what you are looking for, but you could use styles and select the control you are interested in:

<views:MyControl>
  <views:MyControl.Styles>
    <Style Selector="Button#Button1">
      <Setter Property="Content" Value="Hello From Window XAML"/>
    </Style>
  </views:MyControl.Styles>
</views:MyControl>

You can read more about selectors here

  • Related