我正在向动态创建的参数添加属性。一个属性实现IItemsSource接口,其用法如下:
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;
public class MySourceObject
{
[ItemsSource(typeof(MyCustomItemsSource))]
public string SelectedString { get; set; }
}
public class MyCustomItemsSource : IItemsSource
{
public MyCustomItemsSource()
{
}
public ItemCollection GetValues()
{
ItemCollection strings = new ItemCollection();
strings.Add("A");
strings.Add("B");
strings.Add("C");
// Here I want to add some items from a collection, passed to the class somehow
return strings;
}
}
如何将自定义对象列表传递给MyCustomItemsSource构造函数?
目前尚不清楚您想对数据做什么。创建属性时,您没有此类型的实例。此属性不是对象的实例,因此您不能传递任何参数,因此必须在运行时创建对象,并且可以通过反射来创建。
您可以使用:
IItemsSource myObject = Activator.CreateInstance<IItemsSource>(obj1, obj2,...);
更新:据我了解,您想要传递类型,然后传递值以添加到列表中,以便添加
public interface IItemsSource
{
List<string> GetValues();
}
class ItemsSourceAttribute : Attribute
{
public IItemsSource Instance { get; set; }
public ItemsSourceAttribute(Type type, params string[] listParams)
{
if (!typeof(IItemsSource).IsAssignableFrom(type))
throw new ArgumentException($"IItemsSource is not assignable from {type.Name}.");
Instance = (IItemsSource) Activator.CreateInstance(type, listParams);
}
}
public class MyCustomItemsSource : IItemsSource
{
private List<string> _privateList;
public MyCustomItemsSource(params string[] list)
{
_privateList = list.ToList();
}
public List<string> GetValues()
{
// _privateList will start with a value of [abc, 123], as we passed on the constructor.
_privateList.Add("test");
// now [abc, 123, test]
return _privateList;
}
}
然后您可以像这样将项目添加到列表中:
[ItemsSource(typeof(MyCustomItemsSource), "abc", "123"]
希望我做对了。如果您需要任何调整,请发表评论。我写这篇文章时没有进行测试,因为我现在不在这台机器上使用VS。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句