XAML中的ComboBox数据过滤 [英] ComboBox data filtering in xaml

查看:127
本文介绍了XAML中的ComboBox数据过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Telerik组合框,但我认为问题与标准wpf组合框有关。该控件绑定到一个可观察到的 TableRecord集合,该对象看起来像这样:

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

这些 TableRecords的保存和公开如下:

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

我的xml看起来像这样:

My xaml looks like this:

<telerik:RadComboBox ItemsSource="{Binding Commands}" DisplayMemberPath="DisplayName" SelectedValuePath="Id" Height="22" SelectedItem="{Binding SelectedCommand, Mode=TwoWay}" />

我要做的是更改xaml(如果可能),以便显示其中的所有项目除了将状态值设置为已删除的项目之外。

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.

推荐答案

最好的方法是使用CollectionViewSource进行过滤。

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>

在后面的代码中,为集合视图源设置Filter回调,

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

这篇关于XAML中的ComboBox数据过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆