ComboBox data filtering in xaml

一世执手 提交于 2019-12-25 04:15:17

问题


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.


回答1:


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;
        }
    }


来源:https://stackoverflow.com/questions/16935557/combobox-data-filtering-in-xaml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!