【发布时间】:2021-04-26 18:21:51
【问题描述】:
我正在尝试在自定义组件中实现下拉属性,并使用This SO Answer 和this answer 作为指导。
到目前为止,我设法通过下拉列表中的预定义项目使其正常工作。
但是我还需要弄清楚如何更改下拉列表中的项目?
这是我到目前为止的代码(从上面提到的链接构建)
[TypeConverter(typeof(TableNameConverter))]
public TableName gttTableName
{ get; set; }
...
public class TableName
{
public string Name { get; set; }
public override string ToString()
{
return $"{Name}";
}
}
public class TableNameService
{
List<TableName> list = new List<TableName>() {
new TableName() {Name = "naam 1" },
new TableName() {Name = "naam 2" },
};
public IEnumerable<TableName> GetAll()
{
return list;
}
}
public class TableNameConverter : TypeConverter
{
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
var svc = new TableNameService();
return new StandardValuesCollection(svc.GetAll().ToList());
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return true;
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
return true;
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value != null && value.GetType() == typeof(string))
{
var v = $"{value}";
//var id = int.Parse(v.Split('-')[0].Trim());
var name = v.ToString();
var svc = new TableNameService();
//return svc.GetAll().Where(x => x.Id == id).FirstOrDefault();
return svc.GetAll().Where(x => x.Name == name).FirstOrDefault();
}
return base.ConvertFrom(context, culture, value);
}
}
在 VS 属性窗口中是这样的
现在的问题是,当某个属性更改时,下拉属性中的项目必须更改。这应该在方法UpdateTableNames(代码如下)中完成。
换句话说,在另一个属性的设置器中,项目naam 1、naam 2 可以更改为一个完整的新集合,具有更多或更少的项目和不同的值。
我还想不通的是如何更改这些项目?
让我解释一下情况。
- 用户将自定义组件拖放到表单上
- 当他查看属性 gttTableName 时,现在将显示
naam 1和naam 2 - 现在用户更改了另一个属性 (gttDataModule),并且在此属性的设置器中,gttTableName 属性的项目可以更改。
- 因此,如果他再次查看属性 gttTableName,它现在应该会显示完整的其他值列表。
gttDataModule 属性的代码是这样的
public gttDataModule gttDataModule
{
get { return _gttDataModule; }
set
{
_gttDataModule = value;
UpdateTableNames();
}
}
private void UpdateTableNames()
{
List<string> tableNames = new List<string>();
if (_gttDataModule != null)
{
foreach (gttDataTable table in _gttDataModule.gttDataTables)
{
tableNames.Add(table.Table.TableName);
}
}
// at this point the list tableNames will be populated with values.
// What I need is to replace the list in TableNameService from 'naam 1', 'naam 2'
// to the values in this list.
// so they won't be 'naam 1' and 'naam 2' anymore
// It could be more or less items or even none
// They could have different values
// for example the list could be 'tblBox', 'tblUser', tblClient', tblOrders'
// or it could be empty
// or it could be 'vwCars', 'tblSettings'
}
如何更改TableNameService 的list 中的项目?
【问题讨论】:
标签: c# .net winforms custom-component propertygrid