Reputation: 4684
I derived ImageButton from Button class. I want to be able to set text on it using custom property.
ImageButton XAML
<Button x:Class="MyProject.ImageButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="50" Width="75" Template="{DynamicResource BlueButton}">
<StackPanel>
<TextBlock Text="{Binding Path = ImageButton.ButtonText}" TextWrapping="Wrap" Foreground="White"/>
</StackPanel>
</Button>
ImageButton code behind
public partial class ImageButton : Button
{
public string ButtonText
{
get { return (string)GetValue(ButtonTextProperty); }
set { SetValue(ButtonTextProperty, value); }
}
public static readonly DependencyProperty ButtonTextProperty =
DependencyProperty.Register("ButtonText", typeof(string), typeof(ImageButton), new UIPropertyMetadata(string.Empty));
public ImageButton()
{
InitializeComponent();
}
}
Client code:
<local:ImageButton Margin="114,15.879,96,15.878" Grid.Row="2" ButtonText="test"/>
No text is being shown on the button. For some reason the binding doesn't seem to be taking place. What am I doing wrong?
Upvotes: 1
Views: 126
Reputation: 54907
You don’t have a DataContext
set, so the data binding doesn’t know which source object it should bind to.
I find that the easiest way to resolve this is to give your outer control a name, and reference it using ElementName
in your binding:
<Button x:Class="MyProject.ImageButton"
x:Name="myImageButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="50" Width="75" Template="{DynamicResource BlueButton}">
<StackPanel>
<TextBlock Text="{Binding ElementName=myImageButton, Path=ButtonText}"
TextWrapping="Wrap" Foreground="White"/>
</StackPanel>
</Button>
Upvotes: 3
Reputation: 11601
Change this
<TextBlock Text="{Binding Path = ImageButton.ButtonText}"
to
<TextBlock Text="{Binding Path = ButtonText}"
Upvotes: 0