VIBlend
Home Products Downloads Purchase Support Forum About Blog

Silverlight TreeView with Radio Button

by viblend 16. February 2012 21:15
This post will show you how to add radio buttons to the TreeView items.

In order to display radio buttons in the VIBlend TreeView for Silverlight, you need to set the EnableCheckboxes property to true and also the ListItemType of each TreeViewItem to "RadioButton".

For example:

<viblend:TreeView EnableCheckBoxes="True" Width="280" Height="300" x:Name="TreeView">
    <viblend:TreeViewItem ListItemType="RadioButton" DisplayValue="VIBlend" Value="VIBlend" ImageSource="/Images/user.png">
        <viblend:TreeViewItem ListItemType="RadioButton" DisplayValue="Contacts" Value="Contacts" ImageSource="/Images/contacts.png"/>
        <viblend:TreeViewItem ListItemType="RadioButton" DisplayValue="Desktop" Value="Desktop" ImageSource="/Images/desktop.png"/>
        <viblend:TreeViewItem ListItemType="RadioButton" DisplayValue="Documents" Value="Documents" ImageSource="/Images/documents.png"/>
        <viblend:TreeViewItem ListItemType="RadioButton" DisplayValue="Downloads" Value="Downloads" ImageSource="/Images/folder.png"/>
        <viblend:TreeViewItem ListItemType="RadioButton" DisplayValue="Favorites" Value="Favorites" ImageSource="/Images/favorites.png"/>
        <viblend:TreeViewItem ListItemType="RadioButton" DisplayValue="Music" Value="Music" ImageSource="/Images/music.png"/>
        <viblend:TreeViewItem ListItemType="RadioButton" DisplayValue="Pictures" Value="Pictures" ImageSource="/Images/Pictures.png"/>
        <viblend:TreeViewItem ListItemType="RadioButton" DisplayValue="Searches" Value="Searches" ImageSource="/Images/searches.png"/>
        <viblend:TreeViewItem ListItemType="RadioButton" DisplayValue="Videos" Value="Videos" ImageSource="/Images/videos.png"/>
    </viblend:TreeViewItem>
    <viblend:TreeViewItem ListItemType="RadioButton" DisplayValue="Inbox" Value="Inbox" ImageSource="/Images/folder.png"/>
</viblend:TreeView>

Here's the resulting TreeView:
  

VIBlend Silverlight Controls 6.0 With New Metro UI Themes

by viblend 18. January 2012 16:47

We are happy to announce the availability of VIBlend Silverlight Controls 6.0.  The newest version of VIBlend Silverlight Controls includes a set of new Metro UI Themes - Metro Blue, Metro Green and Metro Orange themes.

To download an evaluation version, please visit our Download page. 

View the updated Online Demo.

 

VIBlend Silverlight Controls 5.1

by viblend 29. September 2011 18:22
The updated version of VIBlend Silverlight Controls has just came out. 
  
What's New: 
 
DataGrid Columns Chooser.
DataGrid Grouping Headers Renderer.
Added support for Silverlight 5 RC.
 
What's Fixed:
 
Resolved an issue regarding the DataGrid scrolling.
Resolved an issue regarding the DataGrid HierarchyItem's rendering.
Resolved an issue regarding the HierarchyItem Templates.
Resolved an issue regarding the DataGrid data binding.
Resolved an issue regarding the DataGrid Dispose logic.
Resolved an issue regarding the DataGrid localization.
Resolved an issue regarding the Scheduler repeating appointments.
Resolved an issue regarding the Scheduler day view rendering.
Resolved an issue regarding the Scheduler Appointment dialog.
Resolved an issue regarding the Scheduler resources binding.
Resolved an issue regarding the Scheduler Appointments layout in Day View.
Resolved an issue regarding the DataTimePicker's date formatting.
Resolved an issue regarding the ComboBox selection. 

Silverlight Ribbon Key Tips

by viblend 6. September 2011 06:07

VIBlend RibbonBar offers an easy way to execute commands using Key Tips.  When an end-user presses the Space or F10 key, Key Tips automatically appear. They disappear when the command associated to a KeyTip is executed, or when the user presses the Esc key or clicks a mouse button.

The example code below demonstrates how to create a KeyTip for a UIElement: 

<viblendRibbonBar:RibbonBar.QuickAccessItems>
      <editors:Button Command="{Binding SaveCommand}" viblendRibbonBar:QuickAccessToolbar.MenuItemText="Save" viblendRibbonBar:KeyTipService.Text="1" viblendRibbonBar:KeyTipService.Command="{Binding SaveCommand}" viblendRibbonBar:KeyTipService.Key="D1"/>
      <editors:Button Command="{Binding RedoCommand}" viblendRibbonBar:QuickAccessToolbar.MenuItemText="Redo" viblendRibbonBar:KeyTipService.Text="2" viblendRibbonBar:KeyTipService.Command="{Binding RedoCommand}" viblendRibbonBar:KeyTipService.Key="D2"/>
      <editors:Button Command="{Binding UndoCommand}" viblendRibbonBar:QuickAccessToolbar.MenuItemText="Undo" viblendRibbonBar:KeyTipService.Text="3" viblendRibbonBar:KeyTipService.Command="{Binding UndoCommand}" viblendRibbonBar:KeyTipService.Key="D3"/>
</viblendRibbonBar:RibbonBar.QuickAccessItems>

The KeyTip.Text property allows you to set the text which will be displayed in the KeyTip. The Command and CommandParameter properties allow you to associate a Command to the KeyTip. The command is executed when the user presses the Key associated to the KeyTip.

The sample code below demonstrates how to create the commands from the above code.

C#

public RibbonCommand SaveCommand { get; set; }
public RibbonCommand UndoCommand { get; set; }
public RibbonCommand RedoCommand { get; set; }

public KeyTips()
{          
    InitializeComponent();

    this.SaveCommand = new RibbonCommand(Save, CanExecuteCommand);
    this.UndoCommand = new RibbonCommand(Undo, CanExecuteCommand);
    this.RedoCommand = new RibbonCommand(Redo, CanExecuteCommand);
    this.ribbonBar1.DataContext = this;
 }

private void Save(object parameter)
{
    MessageBox.Show("Save Command");
}

private void Undo(object parameter)
{
    MessageBox.Show("Undo Command");
}

private void Redo(object parameter)
{
    MessageBox.Show("Redo Command");
}

private bool CanExecuteCommand(object parameter)
{
     return true;
}

VB.NET

Private privateSaveCommand As RibbonCommand
Public Property SaveCommand() As RibbonCommand
    Get
        Return privateSaveCommand
    End Get
    Set(ByVal value As RibbonCommand)
        privateSaveCommand = value
    End Set
End Property
Private privateUndoCommand As RibbonCommand
Public Property UndoCommand() As RibbonCommand
    Get
        Return privateUndoCommand
    End Get
    Set(ByVal value As RibbonCommand)
        privateUndoCommand = value
    End Set
End Property
Private privateRedoCommand As RibbonCommand
Public Property RedoCommand() As RibbonCommand
    Get
        Return privateRedoCommand
    End Get
    Set(ByVal value As RibbonCommand)
        privateRedoCommand = value
    End Set
End Property

Public Sub New()
    InitializeComponent()

    Me.SaveCommand = New RibbonCommand(AddressOf Save, AddressOf CanExecuteCommand)
    Me.UndoCommand = New RibbonCommand(AddressOf Undo, AddressOf CanExecuteCommand)
    Me.RedoCommand = New RibbonCommand(AddressOf Redo, AddressOf CanExecuteCommand)
    Me.ribbonBar1.DataContext = Me
End Sub

Private Sub Save(ByVal parameter As Object)
    MessageBox.Show("Save Command")
End Sub

Private Sub Undo(ByVal parameter As Object)
    MessageBox.Show("Undo Command")
End Sub

Private Sub Redo(ByVal parameter As Object)
    MessageBox.Show("Redo Command")
End Sub

Private Function CanExecuteCommand(ByVal parameter As Object) As Boolean
     Return True
End Function


You can change the KeyTips activation and deactivation keys by using the RibbonBar's KeyTipsActivationKey and KeyTipsDeActivationKey properties. 

Repeating Appointments in VIBlend Scheduler

by viblend 21. June 2011 16:50

In this blog post, we demonstrate how to create and add repeating appointments to the VIBlend Silverlight Scheduler.

To create a repeating appointment in VIBlend Silverlight Scheduler, you can follow these steps:

  • Double-Click on any scheduler cell or right-click to open the built-in context menu and click ‘New Appointment’.
  • In the pop-up window that appears, click the Repeat... checkbox.
  • Choose your desired settings in the Recurrence Dialog and click ‘Ok’.
  • Fill in the appointment's other details.
  • Click Save and Close to confirm the changes.

To make an existing appointment repeat, follow these steps:

  • Double-Click on the appointment and in the pop-up window that appears, click the Repeat... checkbox.
  • Choose your desired settings in the Recurrence Dialog and click ‘Ok’.
  • Fill in the appointment’s other details.
  • Click Save and Close to confirm the changes.

To create a repeating appointment in the code-behind, follow these steps:

  • Create a new Appointment object. Set the appointment’s start, duration, subject, description and location fields.

C#

DateTime appointmentStart = DateTime.Now.Date;
TimeSpan appointmentDuration = new TimeSpan(1, 0, 0);
Appointment lunchBreak = new Appointment(appointmentStart, appointmentDuration, "Lunch Break", "Steamed fillet of trout, served with sour-cream sauce, cucumber salad and boiled potatoes", "Lunch Room 1");

VB .NET

Dim appointmentStart As DateTime = DateTime.Now.Date
Dim appointmentDuration As New TimeSpan(1, 0, 0)
Dim lunchBreak As New Appointment(appointmentStart, appointmentDuration, "Lunch Break", "Steamed fillet of trout, served with sour-cream sauce, cucumber salad and boiled potatoes", "Lunch Room 1")

  • Set the Appointment’s RecurrencePattern property to make it repeat. You can set this property to any class derived from the RecurrencePattern class. VIBlend Scheduler control provides four built-in recurrence patterns represented by the DayRecurrencePattern, MonthRecurrencePattern, YearRecurrencePattern and WeekRecurrencePattern classes. The following code snippet demonstrates how to specify a daily repeating behavior:

C#

lunchBreak.RecurrencePattern = new DayRecurrencePattern(lunchBreak.From, this.viblendScheduler.View.To, 1);

VB .NET

lunchBreak.RecurrencePattern = New DayRecurrencePattern(lunchBreak.From, Me.viblendScheduler.View.To, 1)

          In the daily recurrence pattern, you need to specify the RepeatIndex property which determines the days between two occurences. The default property value is 1.

  • Finally, add the appointment to the Scheduler.
C#

this.viblendScheduler.Appointments.Add(lunchBreak);

VB .NET

Me.viblendScheduler.Appointments.Add(lunchBreak)

Working with the VIBlend DataGrid and Nested Data Structures

by viblend 8. June 2011 22:29

This example demonstrates how to bind the VIBlend DataGrid for Silverlight to a list of invoices that has nested properties. The schema of data source contains the following DataFields / Properties: SalesPerson(string), ShipperCompany(string), ProductName(string), UnitPrice(double),
Quantity(double), Discount(double), ExtendedPrice(double), Freight(double) and Address(Address). The address object has the following properties: City(string), Region(string) and Country(string).

We'll create a Pivot Table with 3 pivot rows - City, Country and Region and 1 pivot column - Shipper Company.

<viblend:DataGrid ItemsSource="{Binding}" x:Name="dataGrid1" Margin="4" Background="White" AutoGenerateColumns="True">
    <viblend:DataGrid.BoundFields>
        <viblend:BoundField Text="Country" DataField="Address.Country" Width="160" SortMode="NotSortable"/>
        <viblend:BoundField Text="City" DataField="Address.City" Width="140" SortMode="NotSortable"/>
        <viblend:BoundField Text="Region" DataField="Address.Region" Width="140" SortMode="NotSortable"/>
        <viblend:BoundField Text="Carrier" DataField="ShipperCompany" Width="140" SortMode="NotSortable" />
        <viblend:BoundField Text="ExtendedPrice" DataField="ExtendedPrice" Width="140" SortMode="NotSortable" />
    </viblend:DataGrid.BoundFields>
    <viblend:DataGrid.BoundPivotRows>
        <viblend:BoundField Text="Country" DataField="Address.Country" Width="160" SortMode="NotSortable"/>
        <viblend:BoundField Text="Region" DataField="Address.Region" Width="160" SortMode="NotSortable"/>
        <viblend:BoundField Text="City" DataField="Address.City" Width="140" SortMode="NotSortable"/>
    </viblend:DataGrid.BoundPivotRows>
    <viblend:DataGrid.BoundPivotColumns>
        <viblend:BoundField Text="Carrier" DataField="ShipperCompany" Width="140" SortMode="NotSortable"/>
    </viblend:DataGrid.BoundPivotColumns>
    <viblend:DataGrid.BoundPivotValues>
        <viblend:BoundValueField Width="120" CellHorizontalContentAlignment="Center" Text="Count of Sales" Function="Count" DataField="ExtendedPrice"></viblend:BoundValueField>
         <viblend:BoundValueField Width="120" CellHorizontalContentAlignment="Right" CellVerticalContentAlignment="Center" CellTextFormatString="{}{0:C}" Text="Amount of Sales" Function="Sum" DataField="ExtendedPrice"></viblend:BoundValueField>
        <viblend:BoundValueField Width="120" CellHorizontalContentAlignment="Right" CellVerticalContentAlignment="Center" CellTextFormatString="{}{0:C}" Text="Avg Sale Amount" Function="Average" DataField="ExtendedPrice"></viblend:BoundValueField>
    </viblend:DataGrid.BoundPivotValues>
</viblend:DataGrid>

The following code generates the sample data in the example:

C#

public PivotTableDemo()
{
    InitializeComponent();
    PrepareGridData();
    this.DataContext = this.lst;
}

public class Invoice
{
    public Invoice(
        string City,
        string Region,
        string Country,
        string SalesPerson,
        string ShipperCompany,
        string ProductName,
        double UnitPrice,
        double Quantity,
        double Discount,
        double ExtendedPrice,
        double Freight)
    {
        this.SalesPerson = SalesPerson;
        this.Address = new Address();
        this.Address.City = City;
        this.Address.Region = string.IsNullOrEmpty(Region) ? "All Regions" : Region;
        this.Address.Country = Country;
        this.ShipperCompany = ShipperCompany;
        this.ProductName = ProductName;
        this.UnitPrice = UnitPrice;
        this.Quantity = Quantity;
        this.Discount = Discount;
        this.ExtendedPrice = ExtendedPrice;
        this.Freight = Freight;
    }

    public string SalesPerson { get; set; }
    public string ShipperCompany { get; set; }
    public Address Address { get; set; }
    public string ProductName { get; set; }
    public double UnitPrice { get; set; }
    public double Quantity { get; set; }
    public double Discount { get; set; }
    public double ExtendedPrice { get; set; }
    public double Freight { get; set; }
}

public class Address
{
    public string City { get; set; }
    public string Region { get; set; }
    public string Country { get; set; }
}

public List<Invoice> lst = new List<Invoice>();
private void PrepareGridData()
{
    try
    {
        StreamResourceInfo sri = Application.GetResourceStream(new Uri("IntegratedDemo;component/Examples/Grid/invoices.tab", UriKind.Relative));
        System.IO.StreamReader sr = new System.IO.StreamReader(sri.Stream);
        string line = null;
        sr.ReadLine();
        while ((line = sr.ReadLine()) != null)
        {
            string[] tabs = line.Split('\t');
            lst.Add(new Invoice(tabs[0], tabs[1], tabs[2], tabs[3], tabs[4], tabs[5], double.Parse(tabs[6]), double.Parse(tabs[7]), double.Parse(tabs[8]), double.Parse(tabs[9]), double.Parse(tabs[10])));
        }
        sr.Close();
    }
    catch (System.Exception)
    {
    }
}

VB .NET

Public Sub New()
    InitializeComponent()
    PrepareGridData()
    Me.DataContext = Me.lst
End Sub

Public Class Invoice
    Public Sub New(ByVal City As String, ByVal Region As String, ByVal Country As String, ByVal SalesPerson As String, ByVal ShipperCompany As String, ByVal ProductName As String, ByVal UnitPrice As Double, ByVal Quantity As Double, ByVal Discount As Double, ByVal ExtendedPrice As Double, ByVal Freight As Double)
        Me.SalesPerson = SalesPerson
        Me.Address = New Address()
        Me.Address.City = City
        Me.Address.Region = If(String.IsNullOrEmpty(Region), "All Regions", Region)
        Me.Address.Country = Country
        Me.ShipperCompany = ShipperCompany
        Me.ProductName = ProductName
        Me.UnitPrice = UnitPrice
        Me.Quantity = Quantity
        Me.Discount = Discount
        Me.ExtendedPrice = ExtendedPrice
        Me.Freight = Freight
    End Sub

    Private privateSalesPerson As String
    Public Property SalesPerson() As String
        Get
            Return privateSalesPerson
        End Get
        Set(ByVal value As String)
            privateSalesPerson = value
        End Set
    End Property
    Private privateShipperCompany As String
    Public Property ShipperCompany() As String
        Get
            Return privateShipperCompany
        End Get
        Set(ByVal value As String)
            privateShipperCompany = value
        End Set
    End Property
    Private privateAddress As Address
    Public Property Address() As Address
        Get
            Return privateAddress
        End Get
        Set(ByVal value As Address)
            privateAddress = value
        End Set
    End Property
    Private privateProductName As String
    Public Property ProductName() As String
        Get
            Return privateProductName
        End Get
        Set(ByVal value As String)
            privateProductName = value
        End Set
    End Property
    Private privateUnitPrice As Double
    Public Property UnitPrice() As Double
        Get
            Return privateUnitPrice
        End Get
        Set(ByVal value As Double)
            privateUnitPrice = value
        End Set
    End Property
    Private privateQuantity As Double
    Public Property Quantity() As Double
        Get
            Return privateQuantity
        End Get
        Set(ByVal value As Double)
            privateQuantity = value
        End Set
    End Property
    Private privateDiscount As Double
    Public Property Discount() As Double
        Get
            Return privateDiscount
        End Get
        Set(ByVal value As Double)
            privateDiscount = value
        End Set
    End Property
    Private privateExtendedPrice As Double
    Public Property ExtendedPrice() As Double
        Get
            Return privateExtendedPrice
        End Get
        Set(ByVal value As Double)
            privateExtendedPrice = value
        End Set
    End Property
    Private privateFreight As Double
    Public Property Freight() As Double
        Get
            Return privateFreight
        End Get
        Set(ByVal value As Double)
            privateFreight = value
        End Set
    End Property
End Class

Public Class Address
    Private privateCity As String
    Public Property City() As String
        Get
            Return privateCity
        End Get
        Set(ByVal value As String)
            privateCity = value
        End Set
    End Property
    Private privateRegion As String
    Public Property Region() As String
        Get
            Return privateRegion
        End Get
        Set(ByVal value As String)
            privateRegion = value
        End Set
    End Property
    Private privateCountry As String
    Public Property Country() As String
        Get
            Return privateCountry
        End Get
        Set(ByVal value As String)
            privateCountry = value
        End Set
    End Property
End Class

Public lst As List(Of Invoice) = New List(Of Invoice)()
Private Sub PrepareGridData()
    Try
        Dim sri As StreamResourceInfo = Application.GetResourceStream(New Uri("IntegratedDemo;component/Examples/Grid/invoices.tab", UriKind.Relative))
        Dim sr As New System.IO.StreamReader(sri.Stream)
        Dim line As String = Nothing
        sr.ReadLine()
        line = sr.ReadLine()
        Do While line IsNot Nothing
            Dim tabs() As String = line.Split(ControlChars.Tab)
            lst.Add(New Invoice(tabs(0), tabs(1), tabs(2), tabs(3), tabs(4), tabs(5), Double.Parse(tabs(6)), Double.Parse(tabs(7)), Double.Parse(tabs(8)), Double.Parse(tabs(9)), Double.Parse(tabs(10))))
            line = sr.ReadLine()
        Loop
        sr.Close()
    Catch e1 As System.Exception
    End Try
End Sub


Note: The 'invoices.tab' file is included in the installation package of VIBlend Controls for Silverlight. The default path to the file is: C:\Program Files\VIBlend\SilverlightControls v.5.0\Source Code\CSharp\Examples\Grid\invoices.tab.

VIBlend Controls for Silverlight v5.0 released with 2 new controls

by viblend 24. May 2011 22:19

We are happy to announce that the new version of VIBlend Controls for Silverlight was just released with 2 new controls - Scheduler and Child Window. The Scheduler control provides the easiest way to integrate rich scheduling and calendar fuctionality in your Silverlight applications. It supports 4 different and fully customizable views - Day View, Week View, WorkWeek View and Month View. as well as data binding capabilities, recurring appointmens, edit dialogs and much more. More information about this control is available on its official page.



The ChildWindow control allows you to display a modal or non-modal popup in your Silverlight applications. When the window is opened in a modal mode, the end-users cannot access any part of the interface outside of the dialog.
The default mode of the control enables the end-users to access the application's user interface.

 If you want to check out the latest release, it is now available for download.

New ChildWindow control coming to VIBlend Silverlight Controls v5.0

by viblend 21. April 2011 19:38

In the next version of VIBlend Controls for Silverlight, we will introduce a new control - Silverlight ChildWindow. The ChildWindow control allows you to direct a user’s attention to a particular activity in your application such as entering data or viewing information. This new control resembles a standard Window and can be displayed in a modal or non-modal popup. When the control is displayed in a modal mode, the interaction with the underlying user interface is blocked.

Built-In Features:

  • Animated Open and Close Effects - the window is opened and closed with a smooth animation.
  • Resizing Support - users can choose to drag edges to resize the window.
  • Modal Mode - when the window is opened in a modal mode, the end-users cannot access any part of the interface outside of the dialog.
  • Non-Modal Mode - this mode enables the end-users to access the application's user interface.
  • Startup Position - you can choose the window's startup position. By default, the window is started at the application's middle-center.
  • Minimized and Maximized states - the window can be maximized or minimized similar to the standard Windows.
  • Application Boundaries Detection - end-users cannot drag or resize the window outside of the application's boundaries.

Silverlight DataGrid – Custom Sorting using SortDescription

by viblend 8. April 2011 19:15

This post will show you how to override the built-in sorting functionality and sort the DataGrid data using the SortDescription class. The data content is sorted when a user clicks a column header.

1. The following example defines a DataGrid with six columns that bind to the Name, Date, Product, Quantity, UnitPrice and SalesAmount properties of the EmployeeSaleRecord class.

     <viblendDataGrid:DataGrid AutoGenerateColumns="True" Height="200" VerticalAlignment="Center" Name="dataGrid" Width="350">
            <viblendDataGrid:DataGrid.BoundFields>               
                <viblendDataGrid:BoundField Text="Name" DataField="Name" Width="160"  CellStyle="{StaticResource textCentered}"/>
                <viblendDataGrid:BoundField Text="Date" DataField="Date" Width="140" />
                <viblendDataGrid:BoundField Text="Product" DataField="Product" Width="140"  CellStyle="{StaticResource textCentered}"/>
                <viblendDataGrid:BoundField Text="Quantity" DataField="Quantity" Width="90"  CellStyle="{StaticResource textCentered}"/>
                <viblendDataGrid:BoundField Text="Unit Price" DataField="UnitPrice" Width="74"/>
                <viblendDataGrid:BoundField Text="Sales Amount" DataField="SalesAmount" Width="88"/>
            </viblendDataGrid:DataGrid.BoundFields>
        </viblendDataGrid:DataGrid>


2. Create column header templates with up and down arrow elements that will be displayed when the grid data is sorted.

    <UserControl.Resources>
        <Style x:Name="textCentered" TargetType="viblendDataGrid:GridCellElement">
            <Setter Property="HorizontalContentAlignment" Value="Center" />
            <Setter Property="VerticalContentAlignment" Value="Center" />
        </Style>

        <DataTemplate x:Key="SortAscendingTemplate">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"></ColumnDefinition>
                    <ColumnDefinition Width="Auto"></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <TextBlock Text="{Binding}"></TextBlock>
                <Path Grid.Column="1" x:Name="sortAscElement" Height="5" Width="9" Stretch="Fill" Stroke="#FFFFFFFF" Data="M4.5,5 L0,0 L9,0 z" RenderTransformOrigin="0.0,0.0">
                    <Path.Fill>
                        <LinearGradientBrush EndPoint="-0.237,0.525" StartPoint="0.679,0.525">
                            <GradientStop Color="#55FFFFFF"/>
                            <GradientStop Color="#55FFFFFF" Offset="0.991"/>
                        </LinearGradientBrush>
                    </Path.Fill>
                </Path>
            </Grid>
        </DataTemplate>
        <DataTemplate x:Key="SortDescendingTemplate">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"></ColumnDefinition>
                    <ColumnDefinition Width="Auto"></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <TextBlock Text="{Binding}"></TextBlock>
                <Path Grid.Column="1" x:Name="sortDescElement" Height="5" Width="9" Stretch="Fill" Stroke="#FFFFFFFF" Data="M4.5,0 L9,5 L0,5 z" RenderTransformOrigin="0.0,0.0" >
                    <Path.Fill>
                        <LinearGradientBrush EndPoint="-0.237,0.525" StartPoint="0.679,0.525">
                            <GradientStop Color="#55FFFFFF"/>
                            <GradientStop Color="#55FFFFFF" Offset="0.991"/>
                        </LinearGradientBrush>
                    </Path.Fill>
                </Path>
            </Grid>
        </DataTemplate>
    </UserControl.Resources>


3. Create  CollectionViewSource, HierarchyItem and bool? fields in the code behind.
4. Bind the DataGrid to a List of EmployeeSaleRecord objects. Set the selection mode to row selection and hide the row headers.

    C#

    // Bind DataGrid
    dataGrid.ItemsSource = listSaleRecord;
    dataGrid.SelectionMode = DataGrid.SELECTION_MODE.FULL_ROW_SELECT;
    dataGrid.RowsHierarchy.Visible = false; 

     VB .NET
    ' Bind DataGrid
    dataGrid.ItemsSource = listSaleRecord
    dataGrid.SelectionMode = DataGrid.SELECTION_MODE.FULL_ROW_SELECT
    dataGrid.RowsHierarchy.Visible = False

5. To sort the data according to the contents of a column, the example defines an event handler to handle the HierarchyItemMouseClick event that occurs when you press the column header.  In the event handler, toggle the sorting order and set the DataTemplate property of the HierarchyItem object depending on the sort order. Call the Sort method and  set the DataGrid.ItemsSource property to point to the view. Doing this, the DataGrid will be refreshed and sorted.
      

       C#
       // Subscribe to HierarchyItemMouseClick event.
      dataGrid.HierarchyItemMouseClick += new DataGrid.HierarchyItemMouseButtonEventHandler(dataGrid_HierarchyItemMouseClick);

      void dataGrid_HierarchyItemMouseClick(object sender, HierarchyItemMouseButtonEventArgs args)
        {
            if (clickedItem != null && !args.HierarchyItem.BoundField.DataField.Equals(clickedItem.BoundField.DataField))
            {
                clickedItem.BoundField.DataTemplate = null;
                ascending = null;
            }

            clickedItem = args.HierarchyItem;
            clickedItem.BoundField.DataContext = clickedItem.BoundField.DataField;

            // Load the column's DataTemplate
            if (ascending == null)
            {
                ascending = true;
                clickedItem.BoundField.DataTemplate = this.Resources["SortDescendingTemplate"] as DataTemplate;
            }
            else if (ascending.HasValue && !ascending.Value)
            {
                ascending = null;
                clickedItem.BoundField.DataTemplate = null;
            }
            else if (ascending.HasValue && ascending.Value)
            {
                ascending = false;
                clickedItem.BoundField.DataTemplate = this.Resources["SortAscendingTemplate"] as DataTemplate;
            }

            if (ascending == null)
            {
                dataGrid.ItemsSource = listSaleRecord;
            }
            else
            {
                SortDescription sortDescription = new SortDescription(args.HierarchyItem.BoundField.DataField, ascending == true ? ListSortDirection.Ascending : ListSortDirection.Descending);
                ICollectionView view = Sort(sortDescription, args.HierarchyItem.BoundField.DataField, this.listSaleRecord);
                dataGrid.ItemsSource = view;
            }
        }

      VB .NET

      ' Subscribe to HierarchyItemMouseClick event.
      Private dataGrid.HierarchyItemMouseClick += New DataGrid.HierarchyItemMouseButtonEventHandler(AddressOf dataGrid_HierarchyItemMouseClick)

      Private Sub dataGrid_HierarchyItemMouseClick(ByVal sender As Object, ByVal args As HierarchyItemMouseButtonEventArgs)
            If clickedItem IsNot Nothing AndAlso (Not args.HierarchyItem.BoundField.DataField.Equals(clickedItem.BoundField.DataField)) Then
                clickedItem.BoundField.DataTemplate = Nothing
                ascending = Nothing
            End If

            clickedItem = args.HierarchyItem
            clickedItem.BoundField.DataContext = clickedItem.BoundField.DataField

            ' Load the column's DataTemplate
            If ascending Is Nothing Then
                ascending = True
                clickedItem.BoundField.DataTemplate = TryCast(Me.Resources("SortDescendingTemplate"), DataTemplate)
            ElseIf ascending.HasValue AndAlso (Not ascending.Value) Then
                ascending = Nothing
                clickedItem.BoundField.DataTemplate = Nothing
            ElseIf ascending.HasValue AndAlso ascending.Value Then
                ascending = False
                clickedItem.BoundField.DataTemplate = TryCast(Me.Resources("SortAscendingTemplate"), DataTemplate)
            End If

            If ascending Is Nothing Then
                dataGrid.ItemsSource = listSaleRecord
            Else
                Dim sortDescription As New SortDescription(args.HierarchyItem.BoundField.DataField,If(ascending = True, ListSortDirection.Ascending, ListSortDirection.Descending))
                Dim view As ICollectionView = Sort(sortDescription, args.HierarchyItem.BoundField.DataField, Me.listSaleRecord)
                dataGrid.ItemsSource = view
            End If
      End Sub

6. Implement the Sort method. Add the SortDescription instance to the CollectionViewSource and return the view which will be used as DataGrid items source.

      C#

       public virtual ICollectionView Sort(SortDescription sortDescription, string columnName, System.Collections.IEnumerable itemsSource)
        {
            if (sortDescription == null)
                return null;

            string displayMember = columnName;

            if (String.IsNullOrEmpty(displayMember))
            {
                displayMember = "";
            }

            viewSource.SortDescriptions.Clear();
            if (itemsSource != null)
            {
                if (itemsSource as ICollectionView != null)
                {
                    viewSource.Source = (itemsSource as ICollectionView).SourceCollection;
                }
                else
                {
                    viewSource.Source = itemsSource;
                }

                viewSource.SortDescriptions.Add(sortDescription);
                return viewSource.View;
            }

            return null;
        }

     VB .NET

     Public Overridable Function Sort(ByVal sortDescription As SortDescription, ByVal columnName As String, ByVal itemsSource As System.Collections.IEnumerable) As ICollectionView
            If sortDescription Is Nothing Then
                Return Nothing
            End If

            Dim displayMember As String = columnName

            If String.IsNullOrEmpty(displayMember) Then
                displayMember = ""
            End If

            viewSource.SortDescriptions.Clear()
            If itemsSource IsNot Nothing Then
                If TryCast(itemsSource, ICollectionView) IsNot Nothing Then
                    viewSource.Source = (TryCast(itemsSource, ICollectionView)).SourceCollection
                Else
                    viewSource.Source = itemsSource
                End If

                viewSource.SortDescriptions.Add(sortDescription)
                Return viewSource.View
            End If

            Return Nothing
     End Function

 

Download demo project: DataGridCustomSortingDemo.zip

VIBlend Controls for Silverlight v4.0.0 - Released

by viblend 2. February 2011 17:02

We are proud to announce the immediate availability of VIBlend Silverlight Controls v4.0.0 - the next generation of user interface controls for Silverlight from VIBlend.

Highlights of the new features and improvements in the new version are:

  • Smooth scrolling animation in TreeView, ListBox, ComboBox and CheckedListBox,
  • DataGrid Pivot table aggregation functions - StDev, StDevP, Var, VarP ,
  • New Controls: Ribbon Bar, vScrollViewer, DataGrid Pivot Design Panel, DataGrid Grouping Panel
  • New Default Theme for all controls in the package.

 

To help you shorten your learning curve we improved our help documentation, provide the style definitions of our themes and the full source code in C# and VB .NET of our examples.

About the author

Some text that describes me

Tag cloud

Recent comments

Comment RSS
Copyright © 2011 VIBlend  
ALL RIGHTS RESERVED  
 
Terms of Use | Privacy Policy
WinForms Controls Purchase Online About Us
       
DataGrid Navigation Pane Technical Support Blog
ScrollBar TreeView
ListBox ProgressBar Downloads Register
ComboBox Buttons
TabControl Editors Documentation Client Login

VIBlend Blog is powered by BlogEngine.NET