8

WPFのDataGridコントロールで、列をデフォルトの列タイプ(DataGridTextColumnやDataGridCheckBoxColumnなど)の1つに設定し、その列で並べ替えてからその値を変更すると、グリッドが自動的に再並べ替えられます。

ただし、DataGridTemplateColumnを使用する場合(および列の並べ替えを許可する場合)、並べ替えることはできますが、この列のセルの値を変更しても、グリッドは再並べ替えられません。どうすれば自動的に再ソートをトリガーするように誘導できますか?

XAML:

<DataGrid Name="grid" AutoGenerateColumns="False">
  <DataGrid.Columns>
    <DataGridTextColumn Header="First name" Binding="{Binding First}"/>
    <DataGridTemplateColumn Header="Last name" SortMemberPath="Last">
      <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
          <TextBox Text="{Binding Last}"/>
        </DataTemplate>
      </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
  </DataGrid.Columns>
</DataGrid>

バインディング:

ObservableCollection items = new ObservableCollection();
grid.ItemsSource = items;
items.Add(new Character() { First = "Homer", Last = "Simpson" });
items.Add(new Character() { First = "Kent", Last = "Brockman" });
items.Add(new Character() { First = "Montgomery", Last = "Burns" });

関連する場合に備えて、これが私のアイテムクラスです。

public class Character : INotifyPropertyChanged {
    private string first, last;
    public event PropertyChangedEventHandler PropertyChanged;
    private void Notify(string name) {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(name));
    }
    public string First { get { return first; } set { first = value; Notify("First"); } }
    public string Last { get { return last; } set { last = value; Notify("Last"); } }
}
4

6 に答える 6

5

私もこれに対する答えを探しています。私は1つの解決策を見つけました:(それに満足していませんが...)

コレクションが更新されると、次のことができます。

SortDescription sortDescription = grdData.Items.SortDescriptions[0];
grdData.ItemsSource = null;
grdData.ItemsSource = Data;
grdData.Items.SortDescriptions.Add(sortDescription);

醜いですが、それは機能します。最初のアイテムだけを実行する私の例とは異なり、コレクション全体を保存する必要があります。

ただし、問題の1つは、DataGridが並べ替えを示すヘッダーを失うことです。そのため、正しく並べ替えられても、並べ替えの方向を示す矢印が付いた列ヘッダーが選択されなくなります。

于 2011-06-27T16:04:54.647 に答える
4

私はこれが古いことを知っていますが、このDataGridTemplateColumnの再ソートの問題も発生しました。これは、DataGridTextColumnでは発生しません。列ヘッダーの並べ替え方向をそのままにして修正する方法は次のとおりです。

// after updating the collection, remove all SortDescription and add'em back.
SortDescriptionCollection sortDescriptions = new SortDescriptionCollection();
foreach (SortDescription sd in dataGrid.Items.SortDescriptions)
{
    sortDescriptions.Add(sd);
}
dataGrid.Items.SortDescriptions.Clear();

foreach (SortDescription sd in sortDescriptions)
{
    dataGrid.Items.SortDescriptions.Add(sd);
}

これが人々に役立つことを願っています。

于 2014-01-15T20:20:57.573 に答える
1

2016年には、これらの回答はどれもうまくいきませんでした。

いくつかの試行錯誤の後、私はこれを思いつきました、そしてそれはうまくいくようです:

dataGrid.Items.IsLiveSorting = true;
于 2016-11-02T14:57:36.843 に答える
0

DataGridに新しい行を挿入するときに、同様の問題が発生しました。DataGridのアイテムを更新することで、この問題を解決しました。

dataGrid.Items.Refresh()。これにより、並べ替えも復元されます。
DataGridColumn(この場合はDataGridTextColumn)でSortDirectionを設定することを忘れないでください

DataGridの定義:

<DataGrid x:Name="dgCustomers" ItemsSource="{Binding CustomerTable}" AutoGenerateColumns="False" CanUserDeleteRows="True">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Kunden ID" Binding="{Binding Path=KundenID,Mode=TwoWay}" SortDirection="Ascending" />
            <DataGridTextColumn Header="Name" Binding="{Binding Path=Kundenname,Mode=TwoWay}"/>
    </DataGrid.Columns>
</DataGrid>

CSファイル:

private void btnSavecustomerChanges_Click(object sender, RoutedEventArgs e)
{        
    try        
    {
        BL.UpdateCustomerChanges();
        dgCustomers.Items.Refresh();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Fehler beim Speichern", MessageBoxButton.OK, MessageBoxImage.Error);
    }
}
于 2012-07-24T09:41:48.433 に答える
0

VS2010のC#WPFにDataGridがあり、XAML設定に関係なく並べ替えられませんでした。何らかの理由で、この非表示のDataGrid(セカンダリタブ上)には、プライマリDataGridが同様の設定で正常である場合に、並べ替え順序に問題がありました。そのため、DataGridを図式的に並べ替える必要がありました。これが私のメモです:

最初に、2つのDataGrid(プライマリとセカンダリ。2番目の「拡張名」グリッドのみを並べ替えます)のXAMLを実行します。

        <TabControl Grid.Row="1" Name="tabControl1" VerticalAlignment="Top" Style="{StaticResource Section}" Margin="3" Padding="0" FontFamily="Arial" FontSize="10" BorderThickness="0" >
            <TabItem Name="tabCommon" Style="{StaticResource NameTab}">
                <DataGrid Name="grdCommonNames" SelectionChanged="grdCommonNames_SelectionChanged" PreviewKeyDown="grdCommonNames_PreviewKeyDown" Style="{StaticResource NameListGrid}" Focusable="False">
                    <DataGrid.Columns>
                        <DataGridTextColumn Binding="{Binding Name, NotifyOnTargetUpdated=True}" Width="SizeToCells" Header="Name" CellStyle="{StaticResource NameListCol}" SortDirection="Ascending"  />
                        <DataGridTextColumn Binding="{Binding Pronunciation, NotifyOnTargetUpdated=True}" Width="SizeToCells" Header="Pronunciation" CellStyle="{StaticResource NameListRightCol}"/>
                    </DataGrid.Columns>
                </DataGrid>
            </TabItem>
            <TabItem Name="tabExtended" Style="{StaticResource NameTab}">
                <DataGrid Name="grdExtendedNames" SelectionChanged="grdCommonNames_SelectionChanged" PreviewKeyDown="grdCommonNames_PreviewKeyDown" Style="{StaticResource NameListGrid}" >
                    <DataGrid.Columns>
                        <DataGridTextColumn Binding="{Binding Name, NotifyOnTargetUpdated=True}" Width="SizeToCells" Header="Name" CellStyle="{StaticResource NameListCol}" SortDirection="Descending" SortMemberPath="Name"/>
                        <DataGridTextColumn Binding="{Binding Pronunciation, NotifyOnTargetUpdated=True}" Width="SizeToCells" Header="Pronunciation" CellStyle="{StaticResource NameListRightCol}"/>
                    </DataGrid.Columns>
                </DataGrid>
            </TabItem>
        </TabControl>

次に、クリック後に2番目のタブDatagridを並べ替えるコードスニペット。初めてソートするだけなので、ブール値がここにあります。そうすれば、他の列を手動で並べ替えると、最初のタブに戻ってから2番目のタブに戻っても保持されます。

ここで、データグリッドの最初の列の名前は「名前」です。オンクリックスニペット:

        if (!extendSorted)
        {
            SortDescription extSort = new SortDescription("Name", ListSortDirection.Ascending);
            grdExtendedNames.Items.SortDescriptions.Add(extSort);
            extendSorted = true;
        }

他の誰かがコードを介してデータグリッドを並べ替えるのに役立つことを願っています。私たちが見つけた他の例のほとんどは、単純なセットアップではうまく機能しましたが、このデュアルデータグリッドのタブ付きセットアップでは、それはうまくいきませんでした。

于 2011-10-07T02:55:15.267 に答える
0
    If DataGridMain.Items.SortDescriptions.Count > 0 Then
        Dim vSortDescColl As New SortDescriptionCollection
        For Each vSortDesc In DataGridMain.Items.SortDescriptions
            vSortDescColl.Add(vSortDesc)
        Next
        DataGridMain.ItemsSource = Nothing
        DataGridMain.ItemsSource = vCallColl
        For Each vSortDesc In vSortDescColl
            DataGridMain.Items.SortDescriptions.Add(vSortDesc)
            For Each vColumn In DataGridMain.Columns
                If vColumn.SortMemberPath = vSortDesc.PropertyName Then
                    vColumn.SortDirection = vSortDesc.Direction
                    Exit For
                End If
            Next
        Next
    End If
于 2013-01-27T02:29:06.720 に答える