[英]C# Implement interface through delegate
我想创建一个ObservableList<T>
,但是要创建一个DynamicObject
,所以我可以将元素映射为属性。 这就是为什么我必须继承自DynamicObject
而不是ObservableList<T>
。
public class DataFieldList : DynamicObject, ICollection<DataField>, INotifyCollectionChanged
{
private ObservableList<DataField> _list;
public DataFieldList()
{
_list = new ObservableList<DataField>();
}
public Object this[String name]
{
get
{
return _list.FirstOrDefault(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase))?.Value;
}
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = this[binder.Name];
return result != null;
}
}
现在,我仍然需要实现接口,因此可以像ObservableCollection
一样使用该类。 我想使用_list
作为实现这些接口的委托,但这似乎是不可能的...
此功能通过属性的implements
关键字包含在Delphi中:
property Collection: ICollection read _list implements ICollection;
我知道, 这个和这个问题基本上是相同的,但继承的解决方案是不可能的,我的,也是我真的不能只是公开的接口作为属性。 即使对于ICollection<T>
,即使使用起来有点不便,但对于INotifyCollectionChanged
的属性,即使这样做使用起来也不INotifyCollectionChanged
,因为这无法达到目的-如果接口不是由对象实现的,WPF不会注意到任何更改我绑定。
那么,还有什么其他方法来获取类,该类的行为类似于ObservableCollection<T>
但也允许我访问诸如DynamicObject
类的动态属性?
用例是一个网格,该网格获取DataFieldList
的集合作为源以及列名的集合。
<Style BasedOn="{StaticResource {x:Type dxg:GridControl}}" TargetType="{x:Type controls:DataGrid}">
<Setter Property="ItemsSource" Value="{TemplateBinding Rows}">
<Setter Property="ColumnsSource" Value="{TemplateBinding Columns}">
<Setter Property="ColumnGeneratorTemplate">
<Setter.Value>
<DataTemplate>
<ContentControl>
<dxg:GridColumn FieldName="{Binding Name}"/>
</ContentControl>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
在此,“ Rows
属性包含一个数据源,该数据源将行作为DataFieldList
提供。
如果我正确理解您的意思,您应该会得到这样的信息
public class DataField
{
public string Name { get; set; }
public object Value { get; set; }
}
public class PropertiesCollection
{
public PropertiesCollection(IEnumerable<DataField> collection)
{
_collection = collection;
}
private IEnumerable<DataField> _collection;
public object this[string name]
{
get
{
return _collection.FirstOrDefault(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase))?.Value;
}
}
}
public class CustomList : ObservableCollection<DataField>
{
private PropertiesCollection _collection;
public CustomList()
{
_collection = new PropertiesCollection(this);
}
public PropertiesCollection Properties
{
get
{
return _collection;
}
}
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
OnPropertyChanged(new PropertyChangedEventArgs(nameof(Properties)));
base.OnCollectionChanged(e);
}
}
绑定看起来像这样:
<TextBlock Text="{Binding Properties[SomeProperty],Mode=OneWay}">
</TextBlock>
即我只使用合成而不是继承。 不幸的是,我们只需要满足于组合(并且您很清楚C#不支持多重继承。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.