【问题标题】:ComboBox data filtering in xamlxaml 中的 ComboBox 数据过滤
【发布时间】:2013-06-05 08:55:06
【问题描述】:

我使用的是 Telerik 组合框,但我认为这个问题与标准 wpf 组合框有关。该控件绑定到“TableRecord”的可观察集合,该对象如下所示:

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”是这样保存和公开的:

private ObservableCollection<TableRecord<T>> _recordCollection = new ObservableCollection<TableRecord<T>>();
public ObservableCollection<TableRecord<T>>  Commands 
{
    get
    {
           return _recordCollection;
    }
}

我的 xaml 看起来像这样:

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

我想要做的是更改 xaml(如果可能),以便它显示集合中的所有项目,除了“状态”值设置为“已删除”的项目。

我有一个想法,我可以使用数据触发器来做到这一点,因为我过去曾使用它们来根据内容设置文本颜色,但我不确定我是否可以按照我需要的方式进行过滤。

【问题讨论】:

    标签: c# wpf xaml .net-4.5


    【解决方案1】:

    最好的方法是使用 CollectionViewSource 进行过滤。在资源中定义一个集合视图源并对​​其进行键控。

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

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

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

    【讨论】:

    • 谢谢。我使用您的代码作为我的基础,因为我需要以 mvvm 方式进行操作。我使用了“CollectionViewSource”和“ICollectionView”,过滤效果很好。感谢您的建议。
    猜你喜欢
    • 2012-10-23
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多