简体   繁体   中英

How do I fully expose a nested control in a UserControl to the outside?

Let's say I have a very simple UserControl :

<UserControl x:Class="Test.UserControls.MyControl">
    <DockPanel>
        <Label Content="lorem" />
        <Button Name="ButtonFromUserControl" />
    </DockPanel>
</UserControl>

For example, I want to access all properties of the Button from the outside if I add the UserControl in another file. I'm imagining something like this:

 <StackPanel>
     <usercontrols:MyControl Button.Dock="{Binding ButtonDockPosition}"/>
 </StackPanel>

I know that I can create dependency properties for each property to make them accessible, however I don't know yet which may or may not be used later and don't want to add a DP for each of the nested controls' properties.

I'm not sure if this would be the correct way to do it, if there is another way or pattern I'd be interested as well.

Edit:

I also tried to make the Button itself a DP, but that doesnt't let me access its properties:

public static readonly DependencyProperty NestedButtonProperty =
    DependencyProperty.RegisterAttached("NestedButton", typeof (Button), typeof (MyControl),
        new FrameworkPropertyMetadata());
     
     
 public Button NestedButton => ButtonFromUserControl;

I have found a kind of workaround which at least doesn't require me to generate huge amounts of forwarding DPs. Since most (or all?) of the controls' properties can be also set via a Style , I simply made the Style of each control a DP:

public static readonly DependencyProperty ButtonStyleProperty =
    DependencyProperty.RegisterAttached("ButtonStyle", typeof (Style), typeof (MyUserControl),
        new FrameworkPropertyMetadata());

 public Style ButtonStyle
 {
     get { return (Style) GetValue(ButtonStyleProperty); }
     set { SetValue(ButtonStyleProperty, value); }
 }

Bind it in the UserControl :

 <Button Name="InnerButton" Style="{Binding ButtonStyle, ElementName=MyUserControl}" />

Now you can set the properties of the Button with a custom style:

 <userControls:MyUserControl>
    <userControls:MyUserControl.ButtonStyle>
        <Style TargetType="Button">
            <Style.Setters>
                <Setter Property="Content" Value="ButtonContent" />
                <Setter Property="BorderThickness" Value="5" />
                <Setter Property="BorderBrush" Value="Orange" />
            </Style.Setters>
        </Style>
    </userControls:MyUserControl.ButtonStyle>
  </userControls:MyUserControl>
  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM