我有一个包含2个项目的属性网格。国家和地区城市。我在数据库中有1个表:CountryCityTable保存LocationId,Title,ParentId。对于国家,parentId = 0,对于城市,则为countryid。
在我的propertygrid中,我使用这些并在2个组合框中显示。请看我的代码:
namespace ProGrid
{
public class KeywordProperties
{
[TypeConverter(typeof(CountryLocationConvertor))]
public string CountryNames { get; set; }
[TypeConverter(typeof(CityLocationConvertor))]
public string CityNames { get; set; }
}
}
和
namespace ProGrid
{
public class CountryLocationConvertor : StringConverter
{
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
HumanRoles Db = new HumanRoles();
List<LocationsFieldSet> Items = new List<LocationsFieldSet>();
Items = Db.LoadLocations(0,0);
string[] LocationItems = new string[Items.Count];
int count = 0;
foreach (LocationsFieldSet Item in Items)
{
LocationItems[count] = Item.Title;
count++;
}
return new StandardValuesCollection(LocationItems);
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return true;//false : If you want the user to be able to type in a value that is not in the drop-down list.
}
}
public class CityLocationConvertor : StringConverter
{
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
HumanRoles Db = new HumanRoles();
List<LocationsFieldSet> Items = new List<LocationsFieldSet>();
Items = Db.LoadLocations(1,20);
string[] LocationItems = new string[Items.Count];
int count = 0;
foreach (LocationsFieldSet Item in Items)
{
LocationItems[count] = Item.Title;
count++;
}
return new StandardValuesCollection(LocationItems);
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return true;
}
}
}
并且
KeywordProperties Kp = new KeywordProperties();
myPropertyGrid.SelectedObject = Kp;
现在,我希望当用户在propertygrid中更改国家/地区标题时,更新城市列表(只显示这些= countryid的城市)。
此外,在我的班级中,我如何将代码中的数字20( Db.LoadLocations(1,20); )更改为所选的国家/地区ID?
感谢的。
答案 0 :(得分:3)
您需要实现与INotifyPropertyChanged
Microsoft INotifyPropertyChange Documentation
换句话说,当你遇到一处房产时,你需要举办一些活动。据我所知,属性网格会自动检查该类型的事件/接口,并在引发事件时刷新正确的属性节点。
重要的部分是:
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
和
public bool MyBoolProperty
{
get { return myBoolField; }
set
{
myBoolField = value;
NotifyPropertyChanged();
}
}
如果您想做一些PropertyGrid未涵盖的事情,您只需在PropertyChanged
事件中注册自己的方法,并随意做任何事情。