简体   繁体   中英

Filtering an ObservableCollection by using an IValueConverter

I'm building a Windows 8 Metro Application where I need to filter an ObservableCollection . Sadly, the CollectionViewSource-Class in the WinRT-Framework doesn't support filtering so I try to use an IValueConverter for doing so.

My 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}}"/>

My 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();
    }
}

When the IValueConverter is being executed, the parameter "parameter" is null and not a boolean value. What am I doing wrong?

If binding itself does not support bindings you could change the type of the Appointments property so it includes the parameter you want. If your converter only gets called once - you could try to subscribe to the ObservableProperty's CollectionChanged event and raise the PropertyChanged event for Appointments every time it happens.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM