letiagoalves
letiagoalves

Reputation: 11302

Custom control dependency property not working

In my CustomControl I have the following dependency property:

public bool Favorite
{
    get { return (bool)GetValue(FavoriteProperty); }
    set { SetValue(FavoriteProperty, value); }
}

// Using a DependencyProperty as the backing store for Enabled.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty FavoriteProperty =
    DependencyProperty.Register("Favorite", typeof(bool), typeof(FavoriteCustomControl), new PropertyMetadata(false, new PropertyChangedCallback(OnFavoriteChanged)));

private static void OnFavoriteChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
    FavoriteCustomControl control = (FavoriteCustomControl) dependencyObject;
    TextBlock textBlock = (TextBlock) control.GetTemplateChild(HeartPartName);

    if (textBlock != null)
    {
        double opacity = ((bool)e.NewValue) ? 1 : 0.2;
        textBlock.Opacity = opacity;
    }
}

And when I declare in my window:

<custom:FavoriteCustomControl Grid.Row="1" Grid.Column="2" Margin="2" Favorite="true"/>

it works in the designer view but not when I run the application. I debugged the max I could and I only catch one thing that I think it may be the problem:

OnFavoriteChanged callback runs the exacly amount of times that it should but var textBlock is always null. Well not always because in the designer mode I see that opacity changes and so var textBlock is not null.

I am really stuck and I don't know where to look for errors/bugs causing this.

EDIT:

Now I found that OnFavoriteChanged callback is called before OnApplyTemplate() and I think that's why textBlock is null.

Upvotes: 0

Views: 241

Answers (1)

tukaef
tukaef

Reputation: 9224

Why not just use the standard WPF approach:

<TextBlock Opacity="{Binding Path=Favorite, 
    RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type custom:FavoriteCustomControl}}, 
    Converter={StaticResource BoolToOpacityConverter}}"/>

Note: you need to create class BoolToOpacityConverter and define it as a resource. Example here.

Upvotes: 1

Related Questions