As per bitbonk s answer, but I wanted to override the add(T item) method, but you can t, so I created an append(T item) method instead:
public class ObservableSetCollection<T> : ObservableCollection<T> {
public void Append(T item) {
if (Contains(item)) return;
base.Add(item);
}
}
And then in my code behind:
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());
}
}
In the above I have two listboxes, listboxAvailableColumns, which has a list of strings that the user can select by double-clicking, which adds the selection to the second listbox, listboxConsolidationColumns. No duplicates are allowed, and this works perfectly with the ObservableSetCollection exactly as above.
The xaml is simply:
<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>