(並べ替え)LIstViewのHeaderをクリックしてItemをSortする方法
ListSortDirectionを利用してListViewを並べ替えする
ListView
<ListView Name="listView1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" >
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Data1}">
<GridViewColumnHeader Content="Data1" Click="GridViewColumnHeader_Click" />
</GridViewColumn>
<GridViewColumn DisplayMemberBinding="{Binding Data2}">
<GridViewColumnHeader Content="Data2" Click="GridViewColumnHeader_Click" />
</GridViewColumn>
<GridViewColumn DisplayMemberBinding="{Binding Data3}">
<GridViewColumnHeader Content="Data3" Click="GridViewColumnHeader_Click" />
</GridViewColumn>
<GridViewColumn DisplayMemberBinding="{Binding Data4}">
<GridViewColumnHeader Content="Data4" Click="GridViewColumnHeader_Click" />
</GridViewColumn>
<GridViewColumn DisplayMemberBinding="{Binding Data5}">
<GridViewColumnHeader Content="Data5" Click="GridViewColumnHeader_Click" />
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
GridViewColumnHeader_Click
private void GridViewColumnHeader_Click(object sender, RoutedEventArgs e)
{
// ヘッダー名から列名を取得
GridViewColumnHeader columnHeader = (GridViewColumnHeader)sender;
string columnName = (string)columnHeader.Content;
// ListViewのSortDescriptionsを取得
SortDescriptionCollection sortDescriptionCollection = listView1.Items.SortDescriptions;
if (listView1.Items.Count > 1)
{
ListSortDirection sortDirection;
if (sortDescriptionCollection.Count > 0
&& sortDescriptionCollection.First().PropertyName == columnName
&& sortDescriptionCollection.First().Direction == ListSortDirection.Ascending)
{
sortDirection = ListSortDirection.Descending;
}
else
sortDirection = ListSortDirection.Ascending;
// 履歴をクリア
sortDescriptionCollection.Clear();
sortDescriptionCollection.Add(new SortDescription(columnName, sortDirection));
}
}
Loaded
private void Window_Loaded(object sender, RoutedEventArgs e)
{
int seed = Environment.TickCount;
for (int i = 0; i < 10; i++)
{
Random random = new Random(seed++); // 乱数
SampleData sampleData = new SampleData()
{
Data1 = random.Next(5),
Data2 = random.Next(5),
Data3 = random.Next(5),
Data4 = random.Next(5),
Data5 = random.Next(5)
};
List1.Add(sampleData);
}
listView1.ItemsSource = List1;
}
SampleData Class
public class SampleData
{
public int Data1 { get; set; }
public int Data2 { get; set; }
public int Data3 { get; set; }
public int Data4 { get; set; }
public int Data5 { get; set; }
}
参考:ListView「GridViewColumnHeader.Click」
ListViewに「GridViewColumnHeader.Click」を設定して、コードにlistHeader_Clickを追加する
<ListView ItemsSource="{Binding items}" GridViewColumnHeader.Click="listHeader_Click">
参考:ヘッダーのタイトルを取得する
private void listHeader_Click(object sender, RoutedEventArgs e)
{
string header = (string)((GridViewColumnHeader)e.OriginalSource).Content;
}