2017-09-14 112 views
1

当用ComboBoxObservableCollection<Type>作为ItemsSource向用户展示时,如何在SelectedItem绑定的属性中实例化一个类?基于属性设置值实例化一个类

ElementList列表中的元素在parentItem要么是通用类型的Element,或者是一类从Element(例如DigitalOutputButtonTrendGraph)继承的。

XAML:

<StackPanel Orientation="Horizontal"> 
    <TextBlock Width="100" Text="Element Type:" /> 
    <ComboBox Width="300" ItemsSource="{Binding Path=Element.ElementTypeList}" 
       SelectedItem="{Binding Path=Element.SelectedElementType}" /> 
</StackPanel> 

C#代码:

private static ObservableCollection<Type> _elementTypeList 
    = new ObservableCollection<Type> { typeof(Element), typeof(DigitalOutputButton), typeof(TrendGraph) }; 
public static ObservableCollection<Type> ElementTypeList { get { return _elementTypeList; } } 

public Type SelectedElementType { 
    get { return GetType(); } 
    set { 
     if (value != GetType()) { 
      var parentItem = Controller.ConfigurationHandler.FindParentItem(this); 
      var currentItemIndex = parentItem.ElementList.IndexOf(this); 
      parentItem.ElementList[currentItemIndex] = new typeof(value)(); 
     } 
    } 
} 

上面set代码不会建立。但是否有可能以另一种方式实现这种行为?

编辑:好的,这样工作的:

public Type SelectedElementType { 
    get { return GetType(); } 
    set { 
     if (value != GetType()) { 
      var parentItem = Controller.ConfigurationHandler.FindParentItem(this); 
      var currentItemIndex = parentItem.ElementList.IndexOf(this); 
      if (value == typeof(Element)) { 
       parentItem.ElementList[currentItemIndex] = new Element(); 
      } 
      else if (value == typeof(DigitalOutputButton)) { 
       parentItem.ElementList[currentItemIndex] = new DigitalOutputButton(); 
      } 
      else if (value == typeof(TrendGraph)) { 
       parentItem.ElementList[currentItemIndex] = new TrendGraph(); 
      } 
     } 
    } 
} 

但添加时,将是巨大的它有办法做到这一点,是多一点“免费维修”(无需编辑一个新的元素类型)。

+0

您可以从*该集合中设置初始值'SelectedElementType = ElementTypeList.FirstOrDefault()'或任何其他项*。剩下的将由绑定完成。 – Sinatr

+0

@Sinatr不知道你的解决方案将如何帮助我... – Oystein

+0

为什么在getCommand/setter属性中使用'GetType()'绑定到'ComboBox.SelectedItem'?你不必(我的第一个评论适用)或我不明白的东西。看起来你并不打算从代码隐藏中改变'SelectedElementType',然后让视图(绑定)来处理它。 – Sinatr

回答

1
var instance = Activator.CreateInstance(value, Controller, ParentElementGroup, ItemLabel); 
parentItem.ElementList[currentItemIndex] = (TYPE)instance; 

唯一缺失的链接是您的收藏类型,因此可以投射。但那应该是编译时间的知识。

+1

非常好,这正是我所需要的。它是“ParentElementGroup”而不是“parentItem”。但除此之外,将实例强制转换为所有特定元素类继承的泛型类“元素”就像魅力一样工作。 – Oystein

相关问题