开发者

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(Na开发者_运维百科vigated);
    }

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); }
    }


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜