problem sorting ListView by column
I'm having some problem figuring out which listview column header was clicked on. In the XAML, I have this:
ListView Name="myListView" ItemsSource="{Binding MyItemList}" GridViewColumnHeader.Click="ListView_Click"
And once there is a click on the column header, I handle it like this:
private void ListView_Click(object sender, RoutedEventArgs e)
{
GridViewColumnHeader headerClicked = e.OriginalSource as GridViewColumnHeader;
string header = headerClicked.Column.Header as string;
[...]
This is how I've seen sorting by column done in many samples. After this I use the header to figure out which column to sort by, and do the sorting.
My problem is that headerClicked.Column.Header is the displayed name of the column header, which is different for different languages. Is there a way to get some other type o开发者_运维问答f identifier which is not display/language dependant instead of relying on the "header" string?
Thanks!
you can use DisplayMemberBinding:
Binding b = headerClicked.Column.DisplayMemberBinding as Binding;
string header = b != null ? b.Path.Path as string : null;
alternatively, you can declare an attached property for each header with the name to use and use that.
konstantin
Why not make use of IComparer and a custom sorter and disregard the headers all together? This will remove your tie to the UI and what you are displaying and allow you to focus on the business object (model), which is where the focus should be. Using the UI so heavily is never scalable and will create a maintenance headache at some point in time, if it is hasn't already.
The simplest would be to use the Name property (or the Tag property) on the header, alter your xaml like so:
<ListView Height="100" HorizontalAlignment="Left" Margin="10,10,0,0" Name="listView1" VerticalAlignment="Top" Width="234">
<ListView.View>
<GridView>
<GridViewColumn Width="100">
<GridViewColumnHeader Name="Sort1" Content="Header1" Click="Header_Click"/>
</GridViewColumn>
<GridViewColumn Width="100">
<GridViewColumnHeader Name="Sort2" Content="Header2" Click="Header_Click"/>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
Then you could alter your handler like so:
private void Header_Click(object sender, RoutedEventArgs e) {
GridViewColumnHeader header = sender as GridViewColumnHeader;
String sort = header.Name;
// Sort code here...
return;
}
精彩评论