使用DynamicObject模拟DependencyProperties

时间:2012-03-18 08:38:24

标签: c# dependency-properties dynamicobject

我希望创建类似于VS或Blend的某个功能的东西,当选择多个对象时,属性网格显示所有对象共享的任何属性的值,并且不显示任何属性之间的属性对象。

我设法使用动态对象为CLR属性实现此行为:

  • _knownProperties只是之前已请求的属性列表
  • _collection是一个IEnumerable实例
public override bool TryGetMember( GetMemberBinder binder, out object result ) {
    Debug.WriteLine( "Getting " + binder.Name + "..." );

    if (!_knownProperties.Contains( binder.Name ))
        _knownProperties.Add( binder.Name );

    IEnumerator it = _collection.GetEnumerator();

    if (!it.MoveNext()) {
        result = null;
        Debug.WriteLine( "No elements in collection" );
        return true;
    }

    Type t = it.Current.GetType();
    PropertyInfo pinf = t.GetProperty( binder.Name );
    if (pinf == null) {
        result = null;
        Debug.WriteLine( "Property doesn't exist." );
        return true;
    }
    result = pinf.GetValue( it.Current, null );

    if (result == null) {
        Debug.WriteLine( "Null result" );
        return true;
    }
    while (it.MoveNext())
        if (!result.Equals( it.Current.GetType().GetProperty( binder.Name ).GetValue( it.Current, null ) )) {
            result = null;
            Debug.WriteLine( "Null result" );
            return true;
        }

    Debug.WriteLine( "Result: " + result.ToString() );
    return true;
}

我正在通过WPF Bindings访问这些属性。 谁能想到为DependencyProperties实现这个的方法?如果我尝试绑定到对象上的附加属性,我在属性系统中得到ArgumentNullException,根据我的源)

  • {Binding Selection.SomeClrProperty,...}工作正常(Selection是动态对象之一,SomeClrProperty是集合中每个元素的属性。
  • {Binding Selection.(SomeClass.SomeAttachedProperty),...}在属性系统中触发错误

例外:

System.ArgumentNullException was unhandled
Message=Key cannot be null.
Parameter name: key
Source=System
ParamName=key
StackTrace:
   at System.Collections.Specialized.HybridDictionary.get_Item(Object key)
   at System.ComponentModel.PropertyChangedEventManager.PrivateAddListener(INotifyPropertyChanged source, IWeakEventListener listener, String propertyName)
   at System.ComponentModel.PropertyChangedEventManager.AddListener(INotifyPropertyChanged source, IWeakEventListener listener, String propertyName)
   at MS.Internal.Data.PropertyPathWorker.ReplaceItem(Int32 k, Object newO, Object parent)
   at MS.Internal.Data.PropertyPathWorker.UpdateSourceValueState(Int32 k, ICollectionView collectionView, Object newValue, Boolean isASubPropertyChange)
   at MS.Internal.Data.ClrBindingWorker.AttachDataItem()
   at System.Windows.Data.BindingExpression.Activate(Object item)
   ...

1 个答案:

答案 0 :(得分:0)

使用OneTime绑定来阻止WPF尝试在附加属性上放置侦听器:

{Binding Selection.(SomeClass.SomeAttachedProperty), Mode=OneTime, ...}