简体   繁体   中英

silverlight datagrid: sorting column bound to an object

I have datagrid bound to an ObservableCollection. One of the colum is bound to the object itself rather then one the properties:

    <sdk:DataGrid
        ItemsSource="{Binding PersonList}"
        AutoGenerateColumns="False">
        <sdk:DataGrid.Columns>
            <sdk:DataGridTextColumn
                Binding="{Binding}"
                Header="Person"
                SortMemberPath="FirstName"
                />
            <sdk:DataGridTextColumn
                Binding="{Binding FirstName }"
                Header="FirstName"
                />
            <sdk:DataGridTextColumn
                Binding="{Binding LastName }"
                Header="LastName"
                />
        </sdk:DataGrid.Columns>
    </sdk:DataGrid>

I want to make the column bound to the object itself sortable. I thought it would have been enough to make the class Person implement IComparable. But it seems this is not enough:

public class Person : IComparable<Person>
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public override string ToString()
    {
        return string.Format("{0} {1}", FirstName, LastName);
    }

    public int CompareTo(Person other)
    {
        return FirstName.CompareTo(other.FirstName);
    }
}

Try this one, you dont have to create separate column for sorting,

<sdk:DataGrid
        ItemsSource="{Binding PersonList}"
        AutoGenerateColumns="False">
        <sdk:DataGrid.Columns>

            <sdk:DataGridTextColumn
                Binding="{Binding FirstName }"
                Header="FirstName"
                 CanUserSort="True"
                />
            <sdk:DataGridTextColumn
                Binding="{Binding LastName }"
                Header="LastName"
                />
        </sdk:DataGrid.Columns>
    </sdk:DataGrid>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM