当用ComboBox
和ObservableCollection<Type>
作为ItemsSource
向用户展示时,如何在SelectedItem
绑定的属性中实例化一个类?基于属性设置值实例化一个类
在ElementList
列表中的元素在parentItem
要么是通用类型的Element
,或者是一类从Element
(例如DigitalOutputButton
或TrendGraph
)继承的。
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();
}
}
}
}
但添加时,将是巨大的它有办法做到这一点,是多一点“免费维修”(无需编辑一个新的元素类型)。
您可以从*该集合中设置初始值'SelectedElementType = ElementTypeList.FirstOrDefault()'或任何其他项*。剩下的将由绑定完成。 – Sinatr
@Sinatr不知道你的解决方案将如何帮助我... – Oystein
为什么在getCommand/setter属性中使用'GetType()'绑定到'ComboBox.SelectedItem'?你不必(我的第一个评论适用)或我不明白的东西。看起来你并不打算从代码隐藏中改变'SelectedElementType',然后让视图(绑定)来处理它。 – Sinatr