【发布时间】:2018-10-16 10:49:21
【问题描述】:
我目前正在将数据从一个列表框传输到另一个列表框。 使用 WPF 我有:
<Grid>
<ListBox Margin="10,29,194,301" Name="LeftListBox"/>
<ListBox Margin="0,29,16,301" Name="RightListBox" HorizontalAlignment="Right" Width="173" />
<Button Name="AddButton" Height="23" Margin="34,135,227,0" VerticalAlignment="Top"
Click="AddButton_Click">Add >></Button>
<Button Name="RemoveButton" Margin="227,135,34,264"
Click="RemoveButton_Click"><< Remove</Button>
</Grid>
对于我的 C# 代码,我创建了两个方法,通过使用字符串数组和右侧的字符串来加载左侧框的元素。 现在我的问题是我希望将左框的元素放在右框列表的最后一个元素之后的右框中。所以当我点击添加时,它应该执行这个方法:
private void AddButton_Click(object sender, RoutedEventArgs e)
{
// Find the right item and it's value and index
currentItemText = LeftListBox.SelectedValue.ToString();
currentItemIndex = LeftListBox.SelectedIndex;
ObservableCollection<string> oList;
oList = new System.Collections.ObjectModel.ObservableCollection<string>(toRemoveList);
RightListBox.DataContext = oList;
Binding binding = new Binding();
RightListBox.SetBinding(ListBox.ItemsSourceProperty, binding);
(RightListBox.ItemsSource as ObservableCollection<string>).Add(currentItemText);
if (toAddList != null)
{
toAddList.RemoveAt(currentItemIndex);
}
// Refresh data binding
ApplyDataBinding();
}
但问题是,当我从左侧框中选择一个项目,然后单击添加时,它会将新项目添加到右侧框中,但是当我添加第二个项目时,它会替换我添加的最后一个项目第一步。
之后,第二个问题是,如何实现 RemoveButton_Click ?和之前的方法一样吗?
【问题讨论】:
-
您在添加时定义了一个新的
Binding对象。 -
所以最好在构造函数中定义它吧?
-
可以,否则会被覆盖