[英]listbox double-click to add and remove
I am using WPF and C#. 我正在使用WPF和C#。 I have a bit trouble with two listboxes. 我有两个列表框有点麻烦。 When I double-click an item of ListBox1, it would add the item to ListBox2 and then this item should be removed in ListBox1. 当我双击ListBox1的项目时,它会将项目添加到ListBox2,然后在ListBox1中删除此项目。 Adding is working but removing is not working. 添加正在工作但删除无效。 I got error message (look at the picture). 我收到错误消息(看图片)。 Any idea why? 知道为什么吗? What may be wrong? 可能有什么不对?
class Shopping
{
private ObservableCollection<string> _fruits;
public IEnumerable<string> GetFruits()
{
_fruits = new ObservableCollection<string>
{
"Apples",
"Bananas",
"Oranges",
"Grapes",
"Coconut"
};
return _fruits;
}
public GroceriesList()
{
InitializeComponent();
ListBox1.ItemsSource = _shopping.GetFruits();
}
private void ListBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (ListBox1.SelectedItem != null)
{
ListBox2.Items.Add(ListBox1.SelectedItem);
ListBox1.Items.Remove(ListBox1.SelectedItem);
}
}
They are telling you to add/remove from your variable _fruits PARTIALLY because there is an underlying CollectionViewSource. 他们告诉你在变量_fruits PARTIALLY中添加/删除,因为有一个底层的CollectionViewSource。 I would bind the first lb to a list _allFruits and the second lb to a list _selectedFruits. 我会将第一个lb绑定到列表_allFruits,将第二个lb绑定到列表_selectedFruits。 Perform the appropriate add/remove to those lists rather than directly to the lb sources. 对这些列表执行适当的添加/删除,而不是直接对lb源执行。
It would work something like this (possible compile errors since I cut and paste from your question)... 它会像这样工作(因为我从你的问题剪切和粘贴可能的编译错误)...
private ObservableCollection<string> _fruits;
private ObservableCollection<string> _fruitsSelected;
public IEnumerable<string> GetFruits()
{
_fruits = new ObservableCollection<string>
{
"Apples",
"Bananas",
"Oranges",
"Grapes",
"Coconut"
};
return _fruits;
}
public GroceriesList()
{
InitializeComponent();
_fruitsSelected = new ObservableCollection<string>();
ListBox1.ItemsSource = _shopping.GetFruits();
ListBox2.ItemsSource = _fruitsSelected;
}
private void ListBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (ListBox1.SelectedItem != null)
{
_fruitsSelected.Add(ListBox1.SelectedItem);
_fruits.Remove(ListBox1.SelectedItem);
}
}
This will stop your error from happening and permit the binding to operate in a 'wpf' way. 这将阻止您的错误发生,并允许绑定以'wpf'方式运行。 The other difference being that you are using two lists rather than one. 另一个区别是你使用两个列表而不是一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.