Any way to un-register a WPF dependency property?

后端 未结 6 1282
天命终不由人
天命终不由人 2020-12-16 20:14

I\'m running into an unusual problem in my unit tests. The class I\'m testing creates a dependency property dynamically at runtime and the type of that dependency property c

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-16 20:29

    I was facing scenario where I created a custom control that inherits from Selector which is meant to have two ItemsSource properties, HorizontalItemsSource and VerticalItemsSource.

    I don't even use the ItemsControl property, and don't want the user to be able to access it.

    So I read statenjason's great answer, and it gave me a huge POV on how to remove a DP.
    However, my problem was, that since I declared the ItemsSourceProperty member and the ItemsSource as Private Shadows (private new in C#), I couldn't load it at design time since using MyControlType.ItemsSourceProperty would refer to the shadowed variable.
    Also, when using the loop mentioned in is enswer above (foreach DictionaryEntry etc.), I had an exception thrown saying that the collection has changed during iteration.

    Therefore I came up with a slightly different approach where the DependencyProperty is hardcodedly refered at runtime, and the collection is copied to array so it's not changed (VB.NET, sorry):

    Dim dpType = GetType(DependencyProperty)
    Dim bFlags = BindingFlags.NonPublic Or BindingFlags.Static
    
    Dim FromName = 
      Function(name As String, ownerType As Type) DirectCast(dpType.GetMethod("FromName",
        bFlags).Invoke(Nothing, {name, ownerType}), DependencyProperty)
    
    Dim PropertyFromName = DirectCast(dpType.GetField("PropertyFromName", bFlags).
      GetValue(Nothing), Hashtable)
    
    Dim dp = FromName.Invoke("ItemsSource", GetType(DimensionalGrid))
    Dim entries(PropertyFromName.Count - 1) As DictionaryEntry
    PropertyFromName.CopyTo(entries, 0)
    Dim entry = entries.Single(Function(e) e.Value Is dp)
    PropertyFromName.Remove(entry.Key)
    

    Important note: the above code is all surrounded in the shared constructor of the custom control, and I don't have to check wether it's registered, because I know that a sub-class of Selcetor DOES provide that ItemsSource dp.

提交回复
热议问题