WPF数据网格,对包含IP地址的自动生成列进行排序

本文关键字:自动生成 排序 地址 IP 数据网 数据 网格 包含 WPF | 更新日期: 2023-09-27 18:06:14

当使用以下代码时,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>

谢谢

WPF数据网格,对包含IP地址的自动生成列进行排序

尝试使用以下语法在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>