2011-02-16 180 views
2

有沒有辦法讓一個窗口的所有BindingExpression對象?有沒有辦法讓一個窗口的所有BindingExpression對象?

我想要刷新窗體時,需要觸發刷新窗體的數量PropertyChanged事件太高,不是一個好的選擇。我想這樣做,窗體/窗口可以重新查詢所有綁定的另一種方式。

+0

[link]的可能重複(http://stackoverflow.com/questions/1135012) – eFloh 2011-05-27 10:49:44

回答

3

如果您將PropertyChangedPropertyChangedEventArgs的參數設置爲nullString.Empty,則所有屬性的綁定都會更新。

[MSDN Reference]

做它周圍的其他方法是很多更復雜,可能更耗費的性能,我認爲。您需要檢查整個窗口中每個DependencyObject的每個DependencyProperty的綁定。

編輯:寫了做你問以下粗略的擴展方法,這是非常低效的(有可能是改進的餘地,但你仍然處理相當複雜的算法):

public static void UpdateAllBindings(this DependencyObject o) 
{ 
    //Immediate Properties 
    List<FieldInfo> propertiesAll = new List<FieldInfo>(); 
    Type currentLevel = o.GetType(); 
    while (currentLevel != typeof(object)) 
    { 
     propertiesAll.AddRange(currentLevel.GetFields()); 
     currentLevel = currentLevel.BaseType; 
    } 
    var propertiesDp = propertiesAll.Where(x => x.FieldType == typeof(DependencyProperty)); 
    foreach (var property in propertiesDp) 
    { 
     BindingExpression ex = BindingOperations.GetBindingExpression(o, property.GetValue(o) as DependencyProperty); 
     if (ex != null) 
     { 
      ex.UpdateTarget(); 
     } 
    } 

    //Children 
    int childrenCount = VisualTreeHelper.GetChildrenCount(o); 
    for (int i = 0; i < childrenCount; i++) 
    { 
     var child = VisualTreeHelper.GetChild(o, i); 
     child.UpdateAllBindings(); 
    } 
} 
3

僅供參考,當您調用BindingOperations.ClearAllBindings()時,WPF本身就會完成此操作(遍歷所有數據綁定屬性)。 操作的代碼如下:

public static void ClearAllBindings(DependencyObject target) 
{ 
    if (target == null) 
    { 
     throw new ArgumentNullException("target"); 
    } 
    LocalValueEnumerator localValueEnumerator = target.GetLocalValueEnumerator(); 
    ArrayList arrayList = new ArrayList(8); 
    while (localValueEnumerator.MoveNext()) 
    { 
     LocalValueEntry current = localValueEnumerator.Current; 
     if (BindingOperations.IsDataBound(target, current.Property)) 
     { 
      arrayList.Add(current.Property); 
     } 
    } 
    for (int i = 0; i < arrayList.Count; i++) 
    { 
     target.ClearValue((DependencyProperty)arrayList[i]); 
    } 
} 

LocalValueEnumerator是公開的,所以你可以使用它。 您應該能夠輕鬆地從中推導出解決方案。

相關問題