使用IValueConverter过滤ObservableCollection

时间:2012-08-07 13:33:51

标签: c# xaml data-binding windows-runtime

我正在构建一个Windows 8 Metro应用程序,我需要过滤ObservableCollection。遗憾的是,WinRT-Framework中的CollectionViewSource-Class不支持过滤,所以我尝试使用IValueConverter这样做。

我的XAML:

<RadioButton Content="this Week" GroupName="AppointmentFilter" IsChecked="True" Name="rbtnFilter"/>
<RadioButton Content="all" GroupName="AppointmentFilter"/>
<ListView ItemsSource="{Binding Appointments, ConverterParameter={Binding rbtnFilter.IsChecked}, Converter={StaticResource Filter}}"/>

我的IValueConverter:

public class AppointmentListFilter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        ObservableCollection<VMAppointment> appointments = value as ObservableCollection<VMAppointment>;
        bool filter = (bool)parameter;

        if (filter)
        {
            return new ObservableCollection<VMAppointment>(appointments.Where(x => x.Date.CompareTo(DateTime.Now.AddDays(7)) <= 0));
        }
        else
        {
            return appointments;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

当执行IValueConverter时,参数“parameter”为空且不是布尔值。我做错了什么?

1 个答案:

答案 0 :(得分:0)

如果绑定本身不支持绑定,您可以更改Appointments属性的类型,使其包含所需的参数。 如果您的转换器只被调用一次 - 您可以尝试订阅ObservableProperty的CollectionChanged事件,并在每次发生时为Appointments引发PropertyChanged事件。