Reputation: 4723
I am using a Telerik combobox but I think the question is relevant to the standard wpf combobox. The control is bound to an observable collection of “TableRecord” where this object looks like this:
public enum RecordState
{
Orginal, Added, Modified, Deleted
}
public class TableRecord<T>
{
public Guid Id { get; set; }
public string DisplayName { get; set; }
public T Record { get; set; }
public RecordState State { get; set; }
public TableRecord(Guid id, string displayName, T record, RecordState state)
{
Id = id;
DisplayName = displayName;
Record = record;
State = state;
}
}
These “TableRecords” are held and exposed like this:
private ObservableCollection<TableRecord<T>> _recordCollection = new ObservableCollection<TableRecord<T>>();
public ObservableCollection<TableRecord<T>> Commands
{
get
{
return _recordCollection;
}
}
My xaml looks like this:
<telerik:RadComboBox ItemsSource="{Binding Commands}" DisplayMemberPath="DisplayName" SelectedValuePath="Id" Height="22" SelectedItem="{Binding SelectedCommand, Mode=TwoWay}" />
What I want to do is change the xaml (if possible) so that it shows all the items in the collection apart from the items that have the “State” value set to “Deleted”.
I’ve got an idea that I may be able to do this using data triggers as I’ve used them in the past to set text colour based on content but am not sure if I can filter in the way I need.
Upvotes: 0
Views: 2280
Reputation: 4885
Best approach is to use CollectionViewSource for filtering. Define a collection view source in resources and key it.
<Window.Resources>
<CollectionViewSource Source="{Binding Commands}" x:Key="source"/>
</Window.Resources>
<Grid>
<ComboBox VerticalAlignment="Center" HorizontalAlignment="Center" Width="200"
ItemsSource="{Binding Source={StaticResource source}}"
DisplayMemberPath="DisplayName"/>
</Grid>
In code behind, set Filter callback for collection view source,
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
var source = this.Resources["source"] as CollectionViewSource;
source.Filter += source_Filter;
}
private void source_Filter(object sender, FilterEventArgs e)
{
if (((TableRecord) e.Item).State == RecordState.Deleted)
{
e.Accepted = false;
}
else
{
e.Accepted = true;
}
}
Upvotes: 2