簡體   English   中英

無法讓我的 DataGridTemplateColumn 按字母順序排序

[英]Can not get my DataGridTemplateColumn to sort alphabetically

在我的 WPF 應用程序中,我希望能夠對我的 [某些] 列進行排序。 在大多數情況下,我所有的DataGridTextColumn列都按字母順序排序,但我在按字母順序排序時遇到問題的列是兩個: DataGridTemplateColumn 這是我如何設置DataGrid

<DataGrid Name="FooDataGrid"
          CanUserAddRows="False"
          CanUserReorderColumns="False"
          AutoGenerateColumns="False"
          SelectionMode="Single"
          CanUserResizeRows="True">
    <DataGrid.Columns>
      <!--Space for declaring DataGridTextColumn here-->
      <DataGridTemplateColumn Header="Foo Bar" 
                              IsReadOnly="False" 
                              SortMemberPath="FooBar" 
                              CanUserSort="True" 
                              SortDirection="Ascending">
                                    <DataGridTemplateColumn.CellTemplate>
                                        <DataTemplate>
                                            <TextBox Text="{Binding FooBar, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" SpellCheck.IsEnabled="False"/>
                                        </DataTemplate>
                                    </DataGridTemplateColumn.CellTemplate>
      </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

這是我如何填充數據的代碼:

private void InitFooDataGrid() //Gets called in the constructor
{
    FooDataGrid.Items.Clear();
    
    ObservableCollection<Foo> myFooList = GetFooList();

    foreach(Foo foo in ObservableCollection)
    {
        FooDataGrid.Items.Add(foo);
    }
}

最終結果得到了我的預期,能夠點擊列標題並看到我的行被排序。 但我注意到了一些事情:

在此處輸入圖片說明

無論我將它設置為什么SortingDirection升序降序,它都會像這樣對我的行進行排序。 我希望它顯示我的行A->Z而不是Z->A

我錯過了什么? 提前謝謝了。

我認為這些項目根本沒有排序。 當你仔細看:LEN盡管您希望的項目是按降序排列從Z到A自帶大道紅霉素之前。 因此,“A v ”必須在“ Al ”之前。

列排序僅由用戶觸發。 他需要明確單擊列標題。 然后DataGrid處理Button.Click事件以啟動排序。

如果要對表進行(預)排序,則必須使用源集合的ICollectionView

private void InitFooDataGrid() //Gets called in the constructor
{    
  ObservableCollection<Foo> myFooList = GetFooList();
  FooDataGrid.ItemsSource = myFooList;

  // Sort by the property 'FooBar' in ascending order
  CollectionViewSource.GetDefaultView(myFooList)
    .SortDescriptions.Add(
      new SortDescription(nameof(Foo.FooBar), ListSortDirection.Ascending));

  // Alternatively use ItemsControl.Items if you have direct access.
  // ItemsControl.Items also returns a ICollectionView of the source collection
  FooDataGrid.Items 
    .SortDescriptions.Add(
      new SortDescription(nameof(Foo.FooBar), ListSortDirection.Ascending));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM