user3673720 user3673720 - 1 year ago 48
C# Question

Wpf usercontrol with embedded button : change button's content

I have a simple usercontrol with a button in it which i modified.

When I add this usercontrol to my mainwindow, I can only access the usercontrol's properties. How can I access the button content ? Ideally I'd like to have a custom property let's say "TheText" and I changed it like that

<local:MyButtonControl TheText="My text here will be the button content">

This is what I have in the usercontrol "MyButtonControl"

public object TheText
get => (object)GetValue(_text);
set => SetValue(_text, value);
public static readonly DependencyProperty _text =
DependencyProperty.Register("Text", typeof(object), typeof(MyButton), new UIPropertyMetadata(null));

But what Am I supposed to put for binding ? Can't figure it out. Here's the concerned button.

<Button x:Name="button" Content="{Binding ??? }" Style="{StaticResource RoundedButton}"/>

Answer Source

The Binding should look like this:

<Button Content="{Binding Text,
    RelativeSource={RelativeSource AncestorType=UserControl}}" .../>

Note that a correct dependency property declaration would have to use the same name for both the dependency property and the CLR wrapper. There is also a convention to name the identifier field as <PropertyName>Property.

public object Text
    get => (object)GetValue(TextProperty);
    set => SetValue(TextProperty, value);

public static readonly DependencyProperty TextProperty =
    DependencyProperty.Register("Text", typeof(object), typeof(MyButton));

You should certainly also use string as type of a property that is called Text. Or you call the property ButtonContent or something like that.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download