Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attached properties order

What is the order in which attached properties are applied to an object ? I guess I should ignore this, but here my scenario: I've got an attached property to stick the VM to the View, and then, another attached property that depend on the first one. I'm trying to see what happen if the second is set up before the first, but I can't manage to get the error! ie the first ( the model ) is always set up before the second, whatever is the order in xaml. Who is driving the order of assigment? Can I change it?

Now I'm dealing with the late assigmement by subscribing the proeprty change event:

DependencyPropertyDescriptor dd = DependencyPropertyDescriptor.FromProperty(FrameworkElement.DataContextProperty,depo.GetType());
            dd.AddValueChanged(depo, (s, a) =>
            {
                ChangeDatacontext(s as DependencyObject);
            }

and for simulate the problem I setup manually a new datacontext to the object.

Thanks, Felix

like image 740
Felice Pollano Avatar asked Apr 19 '11 07:04

Felice Pollano


1 Answers

I can't directly answer this question, because I never rely on which property is set before the other, but you can manage things with a method that both attached properties use.

here is an example from my current code:

    public static readonly DependencyProperty RuleVMProperty =
        DependencyProperty.RegisterAttached("RuleVM", typeof(DocumentRuleViewModel), typeof(DocumentRuleViewModel), new UIPropertyMetadata(null, RuleVMChanged));

    public static void RuleVMChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
    {
        var el = GetRefid(sender);
        var vm = args.NewValue as DocumentRuleViewModel;
        if(vm==null)
            return;
        vm.SetDocumentFromRefid(sender, el);
    }

    public static readonly DependencyProperty RefidProperty =
        DependencyProperty.RegisterAttached("Refid", typeof(XmlElement), typeof(DocumentRuleViewModel), new UIPropertyMetadata(RefidChanged));

    public static void RefidChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
    {
        var el = args.NewValue as XmlElement;
        var vm = GetRuleVM(sender);
        if (vm == null)
            return;
        vm.SetDocumentFromRefid(sender, el);
    }

    private void SetDocumentFromRefid(DependencyObject sender, XmlElement element)
    {
        ... // this is where the actual logic sits
    }

so essentially you have two changed handlers and whichever triggers last executes the logic because it sees if the other property is null.

like image 166
Markus Hütter Avatar answered Sep 22 '22 16:09

Markus Hütter