如何将 CollectionViewSource 绑定到 DataGrid

How to bind CollectionViewSource to DataGrid

我有一个数据网格,想将其项目源绑定为具有列表源的 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));
    }
    
    }

这应该有效:

<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

public WeightItem()
{
    InitializeComponent();
    loadCaseWeightItems = ...;

    ((CollectionViewSource)Resources["weightItemCollection"]).Source = loadCaseWeightItems;
}