CollectionViewSource绑定到单例中的属性

时间:2015-03-02 14:27:40

标签: c# wpf xaml singleton collectionviewsource

我有这样的单身类

public class Sample
{
    private static readonly Lazy<Sample> lazy =
    new Lazy<Sample>(() => new Sample());

    private ObservableCollection<SampleGroup> _groups;

    public ObservableCollection<SampleGroup> Groups
    {
        get { return _groups; }
    }

}

我将Groups属性绑定到ListView

 <Window.Resources>
    <!-- Data Source For Binding-->
    <CollectionViewSource x:Key="SampleGroups" Source="{Binding Groups}" />
 </Window.Resources>
 ...
 <ListView x:Name="GroupNameListView" 
                                  ItemsSource="{Binding Source={StaticResource SampleGroups}}"
                                  SelectedIndex="0"  SelectionChanged="GroupNameListView_SelectionChanged" >
  ....

为了完成这项工作,我需要将this.DataContext= Sample.Instance放在后面的代码中。

我可以在DataContext部分中指定此<Window.Resources>吗?因为我想添加另一个CollectionViewSource DataContext

1 个答案:

答案 0 :(得分:1)

您可以直接绑定单例类,如下所述。

<CollectionViewSource x:Key="SampleGroups" Source="{Binding Source={x:Static local:Sample.Instance}, Path=Groups}" />
相关问题