【发布时间】:2013-10-10 18:21:23
【问题描述】:
我有一个程序可以更改 comboBox 中显示的项目集合。我之前在this question 中讨论过它。无论如何,我现在正在使用自定义集合,因为observableCollection 没有selectedItem 属性。自定义集合中有一个 selectedItem 属性,但我只是不确定如何设置它以便保存数据。
自定义集合类
public class MyCustomCollection<T>: ObservableCollection<T>
{
private T _mySelectedItem;
public MyCustomCollection(IEnumerable<T> collection) : base(collection) { }
public T MySelectedItem
{
get { return _mySelectedItem; }
set
{
if (Equals(value, _mySelectedItem)) return;
_mySelectedItem = value;
OnPropertyChanged(new PropertyChangedEventArgs("MySelectedItem"));
}
}
}
ViewModel - 我在 comboBox 中更改集合并为每个集合设置 selectedItem
//Property for the selected command in the LIST BOX
//**For clarity: the collection in the comboBox is changed based on what is
//selected in the list box
public string SelectedCommand
{
get { return _selectedCommand; }
set
{
_selectedCommand = value;
NotifyPropertyChange(() => SelectedCommand);
if (SelectedCommand == "1st Collection of type A")
{
ComboBoxEnabled = true;
ComboBoxList = new MyCustomCollection<string>(collectionA);
//collectionA.MySelectedItem = ??(What would I put here?)
}
if (SelectedCommand == "2nd Collection of type A")
{
ComboBoxEnabled = true;
ComboBoxList = new MyCustomCollection<string>(collectionA);
//collectionA.MySelectedItem = ??(What would I put here?)
}
}
}
如何为我创建并添加到comboBox 的每个新集合分配一个值给MySelectedItem?这样,每当我切换到 comboBox 中的不同集合时,selectedItem 就会显示出来。
更新
我的收藏现在设置为ObservableCollection<string>。
ListBox 和 ComboBox 的 XAML
<ListBox ItemsSource="{Binding Model.CommandList}" SelectedItem="{Binding Model.SelectedCommand}" ... />
<ComboBox ItemsSource="{Binding Model.ComboBoxList}" SelectedItem="{Binding Model.SelectedOperation}" ... />
**ListBox 下的新 SelectedCommand 属性:
public string SelectedCommand
{
get { return _selectedCommand; }
set
{
_selectedCommand = value;
NotifyPropertyChange(() => SelectedCommand);
switch (SelectedCommand)
{
case "Collection A":
{
ComboBoxList = CollectionA;
break;
}
case "Collection B":
{
ComboBoxList = CollectionB;
break;
}
}
NotifyPropertyChange(() => ComboBoxList);
}
}
程序仍然没有保留为每个集合选择的selectedItem。我一定是忘记了,或者不明白什么。
【问题讨论】:
-
不确定我理解您为什么决定实施自定义
ObservableCollection。您可以将ComboBox绑定到集合以及选定的项目<ComboBox ItemsSource="{Binding someCollection}" SelectedItem="{Binding someItem}"/> -
我知道,而且行得通。但是,
comboBox的集合和selectedItem取决于在listBox中选择的命令。所以selectedItem不依赖于它存在的每个窗口的一个集合。 -
所以让我直截了当地说,你想要一个
ComboBox,当你更改它的集合时(我假设通过选择列表框中的某些项目),它的SelectedItem变成......什么? -
是的。
selectedItem将是用户选择的任何内容。所以一开始什么都不会。 -
然后只需将您的组合框绑定到一个集合,将其绑定一个 selectedItem,然后在您的列表框的更改命令上更改集合...等等,我将在答案中发布示例代码.. .
标签: c# wpf combobox observablecollection selecteditem