Nick Heiner
Nick Heiner

Reputation: 122432

Silverlight: When is a dependency property available?

I am setting a dependency property in XAML (Silverlight 4):

<my:TopSearchBar x:Name="topSearchBar" Grid.Row="0" Navigator="{Binding ElementName=navigationFrame}" HorizontalAlignment="Stretch" VerticalAlignment="Top" />

I need to register for some navigation events of the navigationFrame. However, the following fails with a null pointer exception:

    public TopSearchBar()
    {
        // Required to initialize variables
        InitializeComponent();

        Loaded += new RoutedEventHandler(TopSearchBar_Loaded);
    }

    void TopSearchBar_Loaded(object sender, RoutedEventArgs e)
    {
        // Navigator is null
        Navigator.Navigated += new NavigatedEventHandler(Navigated);
    }

When is the right time to register these event handlers? I tried doing it in the property setter, but that breakpoint was never hit:

    public Frame Navigator
    {
        get { return GetValue(NavigatorProperty) as Frame; }
        set { SetValue(NavigatorProperty, value); }
    }

Upvotes: 0

Views: 128

Answers (1)

David Yaw
David Yaw

Reputation: 27864

Bindings do not use the Navigator property. Instead, the binding class accesses the NavigatorProperty field, of type DependencyProperty, directly, and sets the value.

In your code behind, you can do an OverrideMetadata on the NavigatorProperty object. Create a PropertyMetadata that includes a PropertyChangedCallback, and add the event handler there. Just be aware, OverrideMetadata works on all instances of the type you specify, so specify the lowest one you need (TopSearchBar, probably), and be careful.

DependencyProperty.OverrideMetadata Method

Upvotes: 2

Related Questions