2011-04-19 70 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