附加属性应用于对象的顺序是什么?我想我应该忽略这一点,但在我的场景中: 我有一个附加属性将VM粘贴到View,然后是另一个依赖于第一个的附加属性。我试图看看如果第二个设置在第一个之前会发生什么,但我无法设法得到错误!即第一个(模型)总是在第二个之前设置,无论xaml中的顺序如何。谁在推动分配令?我可以改变吗?
现在我通过订阅proeprty改变事件来处理迟到的分配:
DependencyPropertyDescriptor dd = DependencyPropertyDescriptor.FromProperty(FrameworkElement.DataContextProperty,depo.GetType());
dd.AddValueChanged(depo, (s, a) =>
{
ChangeDatacontext(s as DependencyObject);
}
并且为了模拟问题,我手动设置了一个新的datacontext到对象。
谢谢, 菲利克斯
答案 0 :(得分: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
}
所以基本上你有两个更改处理程序,无论哪个触发器最后执行逻辑,因为它看到其他属性是否为空。