【问题标题】:Attached properties order附加属性顺序
【发布时间】:2016-05-19 20:49:39
【问题描述】:

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

现在我正在通过订阅属性更改事件来处理延迟分配:

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

为了模拟问题,我手动为对象设置了一个新的数据上下文。

谢谢, 费利克斯

【问题讨论】:

    标签: wpf attached-properties


    【解决方案1】:

    我不能直接回答这个问题,因为我从不依赖哪个属性设置在另一个之前,但是您可以使用两个附加属性都使用的方法来管理事物。

    这是我当前代码中的一个示例:

        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
        }
    

    所以基本上你有两个更改的处理程序,无论哪个触发器最后执行逻辑,因为它会查看另一个属性是否为空。

    【讨论】:

    • 这很好,谢谢。但是如果你有两个不同的对象呢?现在我在对象上订阅 PropertyChange 事件,它对我有用,但我只是好奇为什么一个属性总是设置在另一个之前。
    猜你喜欢
    • 2011-11-01
    • 2010-12-09
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多