在源更改时进行LINQ源更新

时间:2014-08-04 11:46:17

标签: c# linq windows-runtime

我有以下LINQ查询,它为分组CollectionViewSource创建源。问题是当示例更改时(即添加了示例),它不会更新。 而且我不知道如何绑定LINQ查询。

cvsExamplesSource.Source = from example in Examples
                           group example by example.Author into grp
                           orderby grp.Key
                           select grp;

那么,每当发生PropertyChanged事件时,如何更新示例而不必重新加载整个源,我该怎么告诉它更新?

1 个答案:

答案 0 :(得分:0)

建议在XAML中使用新属性ExamplesGrouped绑定 cvsExamplesSource.Source ,如下所示:

<强> XAML:

<SomeList x:Name="cvsExamplesSource" Source="{Binding ExamplesGrouped}"/>

数据上下文类:

public class MyClass : INotifyPropertyChanged /*or derive from ModelViewBase*/
{
    public ObservableCollection<Example> Examples { get; private set; }

    public IEnumerable<IGrouping<String, Example>> ExamplesGrouped
    {
        get
        {
            return from example in Examples
                        group example by example.Author into grp
                        orderby grp.Key
                        select grp; 
        }
    }

    public MyClass()
    {
        Examples = new ObservableCollection<Example>();
        Examples.CollectionChanged += (_, __) => RaisePropertyChanged("ExamplesGrouped");
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void RaisePropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (null != handler)
        {
            handler.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}