根据 bitbonk 的回答,但我想覆盖 add(T item) 方法,但你不能,所以我创建了一个 append(T item) 方法:
public class ObservableSetCollection<T> : ObservableCollection<T> {
public void Append(T item) {
if (Contains(item)) return;
base.Add(item);
}
}
然后在我的代码后面:
public partial class MainWindow : Window {
private ObservableSetCollection<string> consolidationHeaders;
public MainWindow() {
InitializeComponent();
initialize();
}
private void initialize() {
consolidationHeaders = new ObservableSetCollection<string>();
listboxConsolidationColumns.ItemsSource = consolidationHeaders;
}
.
.
.
private void listboxAvailableColumns_MouseDoubleClick(object sender, MouseButtonEventArgs e) {
consolidationHeaders.Append(listboxAvailableColumns.SelectedValue.ToString());
}
private void listboxConsolidationColumns_MouseDoubleClick(object sender, MouseButtonEventArgs e) {
consolidationHeaders.Remove(listboxConsolidationColumns.SelectedValue.ToString());
}
}
在上面我有两个列表框listboxAvailableColumns,它有一个字符串列表,用户可以通过双击来选择,这会将选择添加到第二个列表框listboxConsolidationColumns。不允许重复,这与上面的 ObservableSetCollection 完全一样。
xaml 很简单:
<Grid Margin="5,5,5,5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="1*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="1*" />
</Grid.RowDefinitions>
<Label Grid.Row="0" Grid.Column="0" Margin="0,0,0,0" VerticalAlignment="Center" HorizontalAlignment="Center" Content="Available Columns"/>
<Label Grid.Row="0" Grid.Column="1" Margin="0,0,0,0" VerticalAlignment="Center" HorizontalAlignment="Center" Content="Consolidation Columns"/>
<ListBox Grid.Row="1" Grid.Column="0" Name="listboxAvailableColumns" MouseDoubleClick="listboxAvailableColumns_MouseDoubleClick" />
<ListBox Grid.Row="1" Grid.Column="1" Name="listboxConsolidationColumns" MouseDoubleClick="listboxConsolidationColumns_MouseDoubleClick" />
</Grid>