使用以下代码时,IP地址列不可排序(单击标题并且未触发排序事件时没有任何反应)。如何使IP地址列可排序?
C#:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net;
using System.Windows;
using System.Windows.Controls;
namespace DGrid1
{
public class Item
{
public IPAddress Address { get; set; }
public string Name { get; set; }
}
public partial class MainWindow : Window
{
public ObservableCollection<Item> Collection { get; set; }
public MainWindow()
{
Collection = new ObservableCollection<Item>();
Collection.Add(new Item {Address=IPAddress.Parse("192.168.201.123"), Name="fred" });
Collection.Add(new Item { Address = IPAddress.Parse("192.168.201.241"), Name = "jim" });
InitializeComponent();
this.DataContext = this;
}
private void grid_Sorting(object sender, DataGridSortingEventArgs e)
{
System.Diagnostics.Debug.WriteLine(e.Column);
}
}
}
XAML:
<Window x:Class="DGrid1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid ItemsSource="{Binding Collection}" AutoGenerateColumns="True" x:Name="grid" Sorting="grid_Sorting"/>
</Grid>
</Window>
由于
答案 0 :(得分:2)
尝试使用以下语法手动定义DataGrid的XAML中的每个列:
<DataGrid ItemsSource="{Binding Collection}" AutoGenerateColumns="False" x:Name="grid" Sorting="grid_Sorting">
<DataGrid.Columns>
<DataGridTextColumn Header="IP" Binding="{Binding Address}" SortMemberPath="Address" />
<DataGridTextColumn Header="Name" Binding="{Binding Name}" SortMemberPath="Name" />
</DataGrid.Columns>
</DataGrid>