如何将CollectionViewSource绑定到DataGrid

问题描述

我有一个数据网格,想要将其项目源绑定为具有List源的CollectionViewSource。但是绑定不起作用。请在下面检查我的代码。请注意,由于分组时存在虚拟化问题,我不想使用ObservableCollection。

 <UserControl.Resources>
   <CollectionViewSource x:Key="weightitemCollection" Source="{Binding Path=LoadCaseweightitems}" >
        <CollectionViewSource.sortDescriptions>
            <scm:SortDescription PropertyName="LocalizedGroupName"/>
        </CollectionViewSource.sortDescriptions>
        <CollectionViewSource.GroupDescriptions>
            <PropertyGroupDescription PropertyName="LocalizedGroupName"/>
        </CollectionViewSource.GroupDescriptions>
    </CollectionViewSource>
</UserControl.Resources>

<DataGrid  x:Name="customloadCaseGrid"
              ItemsSource="{Binding Source={StaticResource weightitemCollection}}" />

用户控制代码

public partial class weightitem : INotifyPropertyChanged
   {
   List<weightitemData> loadCaseweightitems;
  public List<weightitemData> LoadCaseweightitems { get { return loadCaseweightitems; } set { loadCaseweightitems = value; OnPropertyChanged(nameof(LoadCaseweightitems)); } }
  public event PropertyChangedEventHandler PropertyChanged;
  
   public weightitem()
    {
        InitializeComponent();
        loadCaseweightitems = new List<weightitemData>();
        //Here i add items to loadCaseweightitems 
    }

  
  
  protected virtual void OnPropertyChanged(string propertyName = null)
    {
        PropertyChanged?.Invoke(this,new PropertyChangedEventArgs(propertyName));
    }
    
    }

解决方法

这应该有效:

<!- HTML-->
<article class="stack_1">
<span class="stack_1_info">Hello stackO)verflow</span>
</article>


<!- HTML-->
<article class="stack_2">
<span class="stack_2_info">Hello StackOverflow</span>
</article>

您还可以通过编程方式设置<UserControl.Resources> <CollectionViewSource x:Key="weightItemCollection" Source="{Binding Path=LoadCaseWeightItems,RelativeSource={RelativeSource AncestorType=UserControl}}" > <CollectionViewSource.SortDescriptions> <scm:SortDescription PropertyName="LocalizedGroupName"/> </CollectionViewSource.SortDescriptions> <CollectionViewSource.GroupDescriptions> <PropertyGroupDescription PropertyName="LocalizedGroupName"/> </CollectionViewSource.GroupDescriptions> </CollectionViewSource> </UserControl.Resources> <Grid> <DataGrid x:Name="customLoadCaseGrid" ItemsSource="{Binding Source={StaticResource weightItemCollection}}" /> </Grid>

Source