Attached properties order
Asked Answered
T

1

6

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

Trio answered 19/4, 2011 at 7:49 Comment(0)
D
3

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.

Dietitian answered 19/4, 2011 at 8:45 Comment(1)
that's work thanks. But what if you have two different object ? Now I'm subscribing the PropertyChange event on the object, and it worked for me, but I'm just curious on why one proeprty is always set before the other.Trio

© 2022 - 2024 — McMap. All rights reserved.