R – UserControl custom DependencyProperties problem


I have a custom UserControl with an image and a label, both of which are set at design-time in the XAML like so: <controls:HomeBarButton Icon="/SuCo;component/Resources/music.png" Text="music"/>

When the control has just an Icon, it looks fine. When I add the Text property, the icon disappears at both design- and run-time and the text label ignores the formatting set in the UserControl and is just black in the upper left corner of the control when the label is centered.

Relevant UserControl XAML:

    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
    <Image x:Name="icon" Width="102" Height="102" VerticalAlignment="Stretch"  Source="{Binding Icon}"/>
    <Label x:Name="label" HorizontalContentAlignment="Center" VerticalAlignment="Bottom" Foreground="White" FontFamily="Calibri" FontSize="24" Padding="0" Content="{Binding Text}"></Label>


        public ImageSource Icon
        get { return (ImageSource)this.GetValue(IconProperty); }
        set { this.SetValue(IconProperty, value); }

    public static readonly DependencyProperty IconProperty = DependencyProperty.Register("Icon", typeof(ImageSource), typeof(HomeBarButton), new FrameworkPropertyMetadata(OnIconChanged));

    private static void OnIconChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        dependencyObject.SetValue(Image.SourceProperty, e.NewValue);

    public string Text
        get { return (string)this.GetValue(TextProperty); }
        set { this.SetValue(TextProperty, value); }

    public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(HomeBarButton), new FrameworkPropertyMetadata(OnTextChanged));

    private static void OnTextChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        dependencyObject.SetValue(Label.ContentProperty, e.NewValue);

What am I doing wrong? 🙁

Best Solution

First, I would change that Label to a TextBlock--you would use Label to associate the text of the label with another control. It seems, from your code, that you are not doing this and only want to display the text. The other thing to check is if your text is being displayed over the top of your icon. I would guess that this is what is happening. Changing to a TextBlock may fix this, if not, you probably should set the height and with of the TextBlock manualy. Just my .02 worth.

Related Question