Skip to main content

Microsoft Silverlight

Answered Question sorting silverlight datagridRSS Feed

(0)

Nikotromus
Nikotromus

Member

Member

1 points

25 Posts

sorting silverlight datagrid

How do I programatically sort a silverlight datagrid?  My datagrid's item source is an observable collection. I would like to default my sort by the 5th field in the datagrid, and then be able to programatically sort based off of events.

 Thanks in advance  

gunjanshah21
gunjansh...

Member

Member

526 points

88 Posts

Re: sorting silverlight datagrid

If you use Silverlight 3 Beta, you could use SortDescriptions property on DataGrid to do this:

using System.ComponentModel;

dataGrid.SortDescriptions.Add(new SortDescription("myProperty", ListSortDirection.Descending));

You can have multiple SortDescriptions and DataGrid will sort the columns in the order in which they appear in the SortDescription collection.

Gunjan [MSFT]

Nikotromus
Nikotromus

Member

Member

1 points

25 Posts

Re: Re: sorting silverlight datagrid

Nuts.  I'm using silverlight 2.

yifung
yifung

Contributor

Contributor

3313 points

540 Posts

Microsoft
Answered Question

Re: Re: sorting silverlight datagrid

Unfortunately, there isn't an easy way to do this in Silverlight 2.  To get everything integrated with the sort glyphs, you'd bascially have to implement your one ICollectionView which I don't recommend.  You could potentially take the public sources and rip out the CollectionView that the DataGrid uses.  If you do that, I'd recommend replacing that as soon as a public CollectionView is introduced in Silverlight 3 so you get any updates and bug fixes.

Yifung Lin [MSFT]

SLMonster
SLMonster

Member

Member

299 points

65 Posts

Re: Re: Re: sorting silverlight datagrid

Hi,

I have recently implemented custom sorting in my datagrid. How is explained below.
Step 1 Create styles fro HEader sortedUp, Sorted Down, and Unsorted as below

 

<Style TargetType="prim:DataGridColumnHeader" x:Key="DataGridLinkColumnHeaderUnsorted" >
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="ContentTemplate"><Setter.Value>
     <DataTemplate>
         <StackPanel Orientation="Horizontal" >
              <HyperlinkButton Content="{Binding}" Tag="{Binding}" Click="Header_Click" ></HyperlinkButton></StackPanel>
       </DataTemplate>
</Setter.Value></Setter>
</Style>

<Style TargetType="prim:DataGridColumnHeader" x:Key="DataGridLinkColumnHeaderUp" >
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="ContentTemplate"><Setter.Value>
    <DataTemplate>
        <StackPanel HorizontalAlignment="Center" Width="{Binding}" Orientation="Horizontal" >
            <HyperlinkButton Content="{Binding}" Tag="{Binding}" Click="Header_Click" ></HyperlinkButton>
            <TextBlock VerticalAlignment="Center" FontFamily="Webdings" Text=" 5"/>
    
    </StackPanel>
   
</DataTemplate></Setter.Value></Setter>
</Style>

Step 2 : define grid with CanUserSortColumns=false. and do not create columns as we are programmaticaly creating them

Setp3 : In code behind, Define below properties

public string CurrentSortColumn { get; set; }
public SortDirection CurrentSortDirection { get; set; }

Step3: write method to populate the datagrid as below

private void _PopulateGrid(){
    myDataGrid.ItemsSource = null;
    myDataGrid.Columns.Clear();
    //Create Col1
    DataGridTextColumn configNameColumn = new DataGridTextColumn();
    configNameColumn.Binding =
new Binding("Col1");
    configNameColumn.Header =
"Col1";
    configNameColumn.Width =
new DataGridLength(500);
    configNameColumn.ElementStyle =
new Style();
    configNameColumn.ElementStyle.TargetType =
typeof(TextBlock);
    configNameColumn.ElementStyle.Setters.Add(
new Setter(TextBlock.TextWrappingProperty, TextWrapping.Wrap));
    SetSortColumnStyle(configNameColumn);
    myDataGrid.Columns.Add(configNameColumn);
    //Create other columns and add to grid

    //Sort my datalist on current sorted column and current direction and bing set as source to my grid
    MyDataList.Sort(new SubmittedReportComparer(CurrentSortDirection, CurrentSortColumn));
    myDataGrid.ItemsSource = SubmittedReportsList;

}

Step4 : SetSortStyleMethod
private void SetSortColumnStyle(DataGridColumn dataGridColumn)
{
   
if (CurrentSortColumn == dataGridColumn.Header.ToString())
   
{
        if (this.CurrentSortDirection == SortDirection.Ascending)
            dataGridColumn.HeaderStyle = this.Resources["DataGridLinkColumnHeaderUp"] as Style;
        else
            dataGridColumn.HeaderStyle = this.Resources["DataGridLinkColumnHeaderDown"] as Style;
    }
    else
    {    //Unsorted
   
    dataGridColumn.HeaderStyle = this.Resources["DataGridLinkColumnHeaderUnsorted"] as Style;
    }
}

Step 5 HEader click event handler to change the sort direction
private void Header_Click(object sender, RoutedEventArgs e){
    var link = sender as HyperlinkButton;
    if (link.Tag.ToString() == CurrentSortColumn){
        ChangeCurentSortDirection();}
    else
    {
        CurrentSortColumn = link.Tag.ToString();
        CurrentSortDirection =
SortDirection.Ascending;
    }
   
PopulateGrid();
}

private void ChangeCurentSortDirection()
{
//changeDirection
    if (CurrentSortDirection == SortDirection.Ascending)
        CurrentSortDirection =
SortDirection.Descending;
    else
        CurrentSortDirection = SortDirection.Ascending;
}

 

hope this helps

 

 

 

avtar
avtar

Member

Member

63 points

69 Posts

Re: Re: sorting silverlight datagrid

Hi Gunjan,

How do I programatically sort a silverlight datagrid? 

My datagrid's item source is an List<String> collection.

I am using Silverlight 3.

I cann't use 

     dg.SortDescriptions.Add(new SortDescription("myProperty", ListSortDirection.Ascending));

Because i don't have property, I have List<string>.

When user click on the column of datagrid following unhandled error pop up.

An unhandled exception ('Unhandled Error in silverlight Applicaiton SortDescription's property name 'COL - Asset' is invalid.
at system.window.page.pagedCollectionView.RefreshOverrid()
at System.Window.Data.PagedCollectionView.RefreshInternal()
at System.Window.Data.PagedCollectionView.RefreshOnDefer();

 Thanks lot.

Please click on "Mark As Answer", if this answered your query partially or fully.

yifung
yifung

Contributor

Contributor

3313 points

540 Posts

Microsoft

Re: Re: sorting silverlight datagrid

CollectionView sorting doesn't work on primitives types.  This is true in WPF as well.  You'll need to wrap your string in a object with a public string property

Yifung Lin [MSFT]
  • Unanswered Question
  • Answered Question
  • Announcement
Microsoft Communities