2011-04-19 81 views
5

将附加属性应用于对象的顺序是什么?我想我应该忽略这一点,但在这里我的场景: 我有一个附加属性将虚拟机粘贴到视图,然后,依赖于第一个附加属性。我试图看看如果第二个设置在第一个之前会发生什么,但我无法设法得到错误!即第一个(模型)总是在第二个之前设置,无论xaml中的顺序如何。谁在驾驶分配顺序?我可以改变它吗?附加属性订单

现在我通过订阅的媒体资源相关联的改变事件处理的assigmement晚:

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

和模拟问题我手动设置一个新的DataContext的对象。

感谢, 菲利克斯

回答

2

我不能直接回答这个问题,因为我从来不靠哪个属性之前,其他设置,但是你可以用这两个附加属性使用方法管理的事情。

这里是我当前的代码示例:

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 
    } 

所以基本上你有两个变化的处理程序和取其触发最后,因为它认为,如果其他属性为null执行的逻辑。

+1

这是工作感谢。但是如果你有两个不同的对象呢?现在我正在订阅对象上的PropertyChange事件,它对我有用,但我只是好奇为什么一个proeprty总是先于另一个设置。 – 2011-04-19 08:53:26