TorbenJ
TorbenJ

Reputation: 4582

Bind DependencyProperty to Label's Text property?

I would like to bind my DependencyProperty to a label of my custom button.

Here is my DependencyProperty:

public static readonly DependencyProperty ButtonTextProperty = DependencyProperty.Register("ButtonText", typeof(string), typeof(MainMenuButton));

public string ButtonText
    {
        get { return (string)GetValue(ButtonTextProperty); }
        set { SetValue(ButtonTextProperty, value); }
    }

And here is my attempt to bind the value to the label:

<TextBlock x:Name="lblButtonText" Margin="16,45.2465" TextWrapping="Wrap" Text="{Binding RelativeSource={RelativeSource Mode=Self}, Path=ButtonText}" VerticalAlignment="Center" TextAlignment="Right" Foreground="White" FontSize="17.333" FontWeight="Bold" FontFamily="Segoe UI Semibold" Height="26.053"/>

This way of binding my DependencyProperties worked several times in other cases but I can't figure out why it doesn't work this time?

How can I solve this problem?

Upvotes: 1

Views: 1391

Answers (2)

Johnny
Johnny

Reputation: 795

Alternatively you could try to bind like this:

First give your custom control a name:

<uc:myControl x:Name="ucName" ButtonText="MyText" .../>

(Remember to import the xmlns, which in this example is called uc)

<Window xmlns:uc="NamespaceToMyUc" ...>

Then bind to it using ElementName:

<TextBlock Text="{Binding ElementName=ucName, Path=ButtonText} ... />

Upvotes: 1

Rachel
Rachel

Reputation: 132548

You are setting the source of your binding to Self, and Self is a TextBlock, and TextBlock does not have a property called ButtonText

You're probably looking to set the source of your binding to a RelativeSource of type MyCustomButton

Text="{Binding Path=ButtonText,
    RelativeSource={RelativeSource AncestorType={x:Type local:MyCustomButton}}}"

Upvotes: 1

Related Questions