我有一个基于功能区的UI,它有一个组合框和一个下拉框。我创建了以下方法来加载这些控件的内容:
对于Combobox:
internal void LoadComboBox(RibbonComboBox YourCbx, List<string> YourList)
{
if (YourCbx.Items.Count > 0)
YourCbx.Items.Clear();
foreach (var curEntry in YourList.ToArray())
{
RibbonDropDownItem newItem = Factory.CreateRibbonDropDownItem();
newItem.Label = curEntry ;
YourCbx.Items.Add(newItem);
}
}对于下拉框:
internal void LoadDDBox(RibbonDropDown YourDD, List<string> YourList)
{
if (YourDD.Items.Count > 0)
YourDD.Items.Clear();
foreach (var curEntry in YourList.ToArray())
{
RibbonDropDownItem newItem = Factory.CreateRibbonDropDownItem();
newItem.Label = curEntry ;
YourDD.Items.Add(newItem);
}
}正如您所看到的,除了需要将不同的窗口控件对象传递给该方法之外,这两个方法几乎相同。所以我想为两个控件创建一个单一的方法,并达到了这个目的:
internal void LoadDropDown<T>(IList<T> YourDD, List<string> YourList, Action<RibbonDropDownItem> addMeth)
{
if (YourDD.Count > 0)
YourDD.Clear();
foreach (var curCS in YourList.ToArray())
{
RibbonDropDownItem newItem = Factory.CreateRibbonDropDownItem();
newItem.Label = curCS;
addMeth(newItem);
}
}然后,对此方法的调用可能如下所示:
LoadDropDown<RibbonDropDown>((IList<RibbonDropDown>)MyDropDownControl, MyList,
(x) => { MyDropDownControl.Items.Add(x); });不幸的是,我得到了一个运行时异常,声明RibbonDropDown不能转换为IList。我现在被困在这里了。有没有人有建议让上面两种方法兼而有之?
发布于 2020-02-09 17:55:59
不幸的是,引用公共基类的想法并没有取得什么成果,因为RibbonDropDown和RibbonComboxBox都是Microsoft.Office.Tools.Ribbon名称空间中的接口,而不是类。
但我现在终于找到了正确的解决方案。在VS中查看两个接口的Items成员时,可以看到它们都实现了IList<RibbonDropDownItem>。所以正确的方法如下所示:
internal void LoadDropDown(IList<RibbonDropDownItem> YourDD, List<string> YourList)
{
if (YourDD.Count > 0)
YourDD.Clear();
foreach (var curCS in YourList.ToArray())
{
RibbonDropDownItem newItem = Factory.CreateRibbonDropDownItem();
newItem.Label = curCS;
YourDD.Add(newItem);
}
}调用这个方法现在看起来像这样(并且工作了!):
LoadDropDown((IList<RibbonDropDownItem>)MyDropDownControl.Items, MyList);无论如何,感谢您找到正确解决方案的灵感!
发布于 2020-02-09 01:29:10
你可以像这样重写你的方法:
internal void LoadDropDown<T>(T YourDD, List<string> YourList, Action<RibbonDropDownItem> addMeth) where T : (AnyBaseTypeForRibbonItems)
{
if (YourDD.Items.Count > 0)
YourDD.Items.Clear();
foreach (var curCS in YourList.ToArray())
{
RibbonDropDownItem newItem = Factory.CreateRibbonDropDownItem();
newItem.Label = curCS;
addMeth(newItem);
}
}并像这样使用它:
LoadDropDown<RibbonDropDown>(MyDropDownControl, MyList,
(x) => { MyDropDownControl.Items.Add(x); });https://stackoverflow.com/questions/60129048
复制相似问题