Tag Archives: UXGridView

UXGridView RC Adds MVVM Data Exporting, Multi Aggregates, Selectors, and more

After going through a series of technology preview releases,  UXGridView is finally topping off with the complete feature sets. Today, I’m excited to announce the immediate availability of UXGridView Release Candidate.

In case you missed the stories, UXGridView is Intersoft’s brand-new data grid built to handle the most demanding line-of-business development requirements – from server-side paging and filtering support, data editing and validation, batch update to data aggregates and data exporting. Each feature is thoughtfully engineered to work best with MVVM pattern implementation. UXGridView runs on both Silverlight and WPF with single identical markups. Learn more about UXGridView here.

In this post, I will share the key highlights of the new features implemented in the UXGridView RC. As defined in the roadmap that I posted in my blog post, the RC milestone will include advanced data-centric features such as data exporting, row virtualization improvements, multi aggregates, custom grouping logics, and a bunch of style selectors and template selectors.

Data Exporting the MVVM-way

In the previous CTPs, you have learned how UXGridView handles real-world data access scenarios like paging, filtering, data validation and editing – all implemented entirely with MVVM design pattern. In this RC release, UXGridView adds data exporting capability which you can implement using the solid MVVM pattern. Unlike other grids, the data exporting in UXGridView supports both server-side and client-side mode. The most advanced mode is the server-side data exporting which allows you to export all rows in the data source even though the UXGridView is paged.

Just because UXGridView supports displaying millions of rows, that doesn’t mean you should. In real-world scenarios, most users browse and look only for a piece of data at a time. So in most cases, you would enable the server-side paging in the UXGridView so it loads only a subset of data at a time. For instances, a Grid with the page size set to 20 will load only 20 rows per page. The data exporting, quite the opposite, requires all data to be fetched before the exporting can execute. That’s one of the key challenges that we managed to address in UXGridView, enabling data exporting to work in harmony with the server paging and other features using the MVVM pattern implementation.

To handle the server-side data operation consistently, we built the data exporting upon the same key component that powers the server paging and filtering, the QueryDescriptor. Perhaps you still recall, QueryDescriptor encapsulates the query definitions which consisted of FilterDescriptors, SortDescriptors and PageDescriptor. That’s just perfect because we can simply use the existing instance of the QueryDescriptor in the ViewModel, and perform re-query that doesn’t include the paging descriptor. If you need a refresh on QueryDescriptor, please head to Data-access the MVVM-way.

The best way to handle the data exporting using MVVM is to implement a DelegateCommand in the ViewModel and bind it to the ExportCommand, a new command property introduced in the RC release. In the Executed handler, you call a server query that returns complete data, and finally pass it to the collection in the ViewModel which is bound to the ExportItems property of UXGridView. Take a look at the following code snippet to learn how it’s done.

public class ServerExportingViewModel : ServerSideOperationViewModel
{
    public ServerExportingViewModel()
        : base()
    {
        this.CanUserExport = true;
        this.ExportCommand = new DelegateCommand(ExecuteExportCommand);
    }

    public void ExecuteExportCommand(object parameter)
    {
        QueryDescriptor exportQueryDescriptor =
                     this.QueryDescriptor.CreateCopy(true, true, false);

        this.ProductsSource.GetData
        (
            exportQueryDescriptor,
            (products) =>
            {
                PagedCollectionView current =
                                   this.Products as PagedCollectionView;
                PagedCollectionView exportedItems =
                                   new PagedCollectionView(products);                    

                exportedItems.CopyDefinitionsFrom(current, true,
                                   false, false, false);

                this.ExportItems = exportedItems;
            },
            (totalItemCount) =>
            {

            },
            (error) =>
            {

            }
        );
    }
}

Quite simple and straightforward, isn’t it? Also notice that the QueryDescriptor now has a CreateCopy, a new time-saving method that returns a clone based on the given source and options. The most important point here is the flexibility that UXGridView offered since it gives you full control over how the data retrieval is done in the ViewModel.

4 Built-in Exporting Data Format

UXGridView allows you to export the data source into four data format – not only one, or two. Users have the choice to export data to HTML, Excel, CSV or just a plain text file. From the user interface perspective, all you need to do is to set the CanUserExport property to true. A tiny, stylish dropdown button will then appear in the status bar, next to the data pager. The available data format is listed in the menu when the dropdown button is clicked, such as shown below.

Exporting user interface

Although the user interface has been well predefined, they are fully customized thanks to the loosely-coupled UI architecture. For instances, you can change the dropdown button to a more stylish callout, or just a plain command button if you preferred.

When the data exporting process completes, you’ll be prompted to save the results to your local computer. The following illustration shows the Excel spreadsheet that contains the exported results.

UXGridView data exported to Excel

UXGridView also offers a number of exporting options such as whether to include column footers, column headers or the group footers in the exported results. For even more fine-grained HTML results, you can customize the style of each generated row and cell output through the ExportCssStyleSelector, another big plus for MVVM implementation!

Style and Template Selectors

UXGridView implements a wealth of style selectors and template selectors, giving the freedom you need to create rich data presentation the way you want. The selector pattern is a first-class MVVM citizen that enables you to write custom logics in a separate class instead of in the view level. You get two benefits immediately: greater reusability and cleaner implementation due to the view/code separation.

One of the most common scenarios, for instances, is to show discontinued products in a different background color, allowing users to quickly distinguish the useful information they need to work with. The following illustration shows the results of a RowStyleSelector implementation.

RowStyleSelector in UXGridView

Another common scenario is to display different information based on specific conditions. For instances, showing a Reorder hyperlink button in the case that the products were out-of-stock. This can be done through an implementation of CellTemplateSelector, see the results below.

CellTemplateSelector in UXGridView

Or how about a more advanced scenario like applying a different background brush in the row header of each different group level? That’s also possible to be done through an implementation of RowGroupHeaderStyleSelector.

RowGroupHeaderStyleSelector in UXGridView

I hope the above illustrations give you a clear idea what the style and template selectors are all about.

To be more exact, UXGridView provides 13 selectors for the row, cell, column header, column footer and group elements. The complete list is as follows:

  • Row Style Selector
  • Row Template Selector
  • Cell Style Selector
  • Cell Template Selector
  • Column Header Style Selector
  • Column Header Template Selector
  • Column Footer Style
  • Column Footer Cell Style
  • Column Footer Cell Template
  • Row Details Template Selector
  • Row Group Header Style Selector
  • Row Group Footer Style
  • Row Group Footer Cell Style

Note that the above selectors have not included the selectors of other elements such as editing and exporting.

Multi Aggregates

Another nice addition in the RC release is the support for multiple aggregates in both the column footer and group footer. It will be definitely useful for line-of-business applications, particularly in financial extensive applications. So here the feature is when you need it.

Multi aggregates support in UXGridView

Custom Grouping

The RC release adds more powerful features allowing developers to fine-tuning the grouping results in UXGridView. While most competing grids used locked-down approaches, UXGridView is quite the opposite. You can now define your own custom groups by writing custom logics in a separate class which is then instantiated in the XAML and assigned to the GroupConverter property of the UXGridViewGroupDescriptor.

The sample in the following illustration groups the products data based on a range of CategoryID values.

Grouping with custom logic

Another popular scenario that can be achieved using the group converter is the value list capability where more meaningful information can be displayed in the group header instead of useless IDs, for instances, displaying the actual name of a category instead of the ID such as shown below.

Grouping with value list

Read-only Binding

Last but not least, among the top requested features is the read-only binding which we managed to ship in the RC release. With the read-only binding expression, you can write a custom logic that determines when a particular row or cell should be read-only (not editable).

UXGridView provides read-only binding at both the row and cell level. The read-only binding expression at row level, if returns true when evaluated, will supersede the read-only binding expression at the cell level. This means that if the read-only binding is specified at the row level and returns a true value, the entire row will no longer editable regardless of the value of the binding expression specified in the cells.

For  examples, consider a scenario where discontinued products should be not editable. In such case, the IsReadOnlyBinding of the UXGridView is bound to the Discontinued property of the product entity. To prevent users to accidentally uncheck the Discontinued value, the same property can be bind to the IsReadOnlyBinding of the UXGridViewColumn. The binding expression at the UXGridView level applies to the rows, while the one at the UXGridViewColumn applies to the cells.

Luckily, the RC release shipped with an example based on the above scenarios. The following illustration shows the discontinued product which can no longer be edited.

IsReadOnlyBinding in UXGridView

WCF RIA SP1 Support

The UXGridView, UXDataPager and UXDataFilter controls in the RC release have been updated to support the recently released WCF RIA SP1. Most notable is the paging support for new data model returned in the children of the navigator properties. The data controls are also backward compatible with the previous WCF RIA.

Download the RC Bits

UXGridView Release Candidate includes complete feature sets and near-RTM quality, which means that you can start using UXGridView to build amazingly rich data-centric applications for the Silverlight and WPF platforms. As you have learned through the series of technology preview releases, each UXGridView feature is uniquely engineered to work best for many MVVM scenarios, making it the industry’s first and most advanced MVVM-ready data grid for the Silverlight and WPF development.

To summarize, the RC release adds a host of exciting new and essential features such as data exporting, style and template selectors, multi aggregates, and much more. We’ve also added many new samples that demonstrate real-world development scenarios such as using different sort member for value list and displaying an image in the cells. The RTM version will add a couple “extra” features, so stay tuned for the next announcement!

Click here to download the RC bits and test-drive the new UXGridView features today. The download package includes latest ClientUI assemblies as well as updated and new samples for both Silverlight and WPF platforms.

Please note that the UXGridView RC is the last public community release. The next milestone would be the UXGridView RTM release together with dozens of new members in ClientUI 5. For now, we’d love to hear what you think about the new features and enhancements available in the RC. Please post your feedback, questions or issues to our community forum.

Best,
Jimmy
Chief Software Architect

UXGridView CTP3: Feature-complete Grid for Silverlight & WPF

I hope you’ve enjoyed the second CTP of our upcoming data controls released a couple weeks ago, which includes MVVM-ready data validation and data editing capabilities, as well as customizable editing control architecture. Make sure you also check out Andry’s blog posts covering the editing features in-depth here and here.

Today, I’m excited to announce the third CTP release of our forthcoming UXGridView control. The release includes the expected feature sets according to the CTP milestone described in my earlier post here, plus a handful of nice additions such as enhanced row details, new expander column, and a sophisticated Gmail-style column checker.

Some of the key highlights in this new CTP are discussed in the following.

QueryDescriptor Enhancement

The QueryDescriptor now includes RaiseQueryChanged() method, thanks to Werner Grift for the nice feedback in the LinkedIn group discussion. With the new method, you can programmatically raise the QueryChanged event in your ViewModel, such as when a related view has changed, or when the view needs to be refreshed due to user interaction like button click (called through the delegate command).

Improved Row Details and Hierarchical Grid

The row details feature receives major update in this new CTP release, which now works with the new expander column. The expander column contains a toggle button which is convenient for users to expand or collapse the row details at runtime, see the illustration below.

Row details with expand button

With the new expander column, it’s now possible to use the row details for more advanced business scenarios, for instances, implementing a hierarchical/nested grid such as in Customer-Orders scenario.

Another interesting scenario is the support to load the child data “on demand” based on the expanded item. UXGridView now includes a new property called ExpandedItem, making it possible for you to bind the child data on demand in the ViewModel. Both WCF RIA and DevForce samples are provided to demonstrate how to achieve such scenario.

Nested UXGridView

Notice that the paging and other settings can be applied individually in the child grid for best performance and results.

New Select Column

When I got the CTP build fresh from the lab, this particular new feature looks to be the most impressive. It’s one of my favorite features, and certainly deserves to be one of yours. Take a look at the screenshot below.

Select column with row checker

Although seems common, the select column feature is not available in any other Silverlight/WPF grids in the market – not the one with correct implementation.

The interesting point about this feature is its automatic checked items persistence capability. This means that if you check all the rows in page 1, then go to page 2, the previously checked items will remain persisted. This behavior also applies consistently in all the grid operations such as sorting and grouping. In the above example, we verified the persistence concept by binding the CheckedItems property to a list box which shows all the checked items regardless of the paged view scope.

With the feature correctly implemented along with the MVVM support, it will be useful in many scenarios in business applications – think of web-based mail applications such as Gmail or Hotmail for examples.

Deferred Scrolling Mode

Another nice feature that we managed to include in this CTP release is the deferred scrolling mode. When enabled, dragging the thumb of the vertical scrollbar will not update the view immediately. Instead, an intuitive visual hint will appear near the scrollbar indicating the target row of the scroll position. See the screenshot below for details.

Deferred scrolling with customizable visual hint

This scrolling mode is particularly useful when you have relatively large amount of rows, and also allowing users to quickly scan the information as they scroll through the viewport.

Standards-Compliant User Experiences

As in our good tradition of development, all Intersoft’s UI controls are designed with the best user experiences that conform to the ISO Standards 9241, including the focus and unfocused behavior, keyboard  navigation using arrow keys, and many more.

In this new CTP release, the UXGridView now shows a dimmed focus visual style when the control doesn’t have focus. This enables users to intuitively responding to the user interface based on the visual state presented in the application. The following illustration shows the unfocused visual state of the UXGridView.

ISO-standards UX

Download the CTP3 Bits

In summary, the CTP3 release includes nearly-complete feature sets of UXGridView planned for final release later this month. So far, the latest CTP includes full MVVM support for server data access, server paging and filtering, data validation, editing, customizable edit controls, row details, multiple selection, checker column, deferred scroll mode, flexible appearance and layout settings, and much more. The final release will include more advanced features such as data exporting, data virtualization, and an advanced column filter interface.

Click here to download the CTP3 bits and test-drive the new UXGridView features today. The download package includes latest ClientUI assemblies as well as updated and new samples for both Silverlight and WPF platforms.

Enjoy the new CTP bits! We’d love to hear what you think about the new features available in CTP3, please post your feedback, questions or issues to our community forum.

All the best,
Jimmy

UXGridView Part 5: Using Custom Editing Controls

In the previous post, I’ve covered the basics of data validation and editing using UXGridView the MVVM-way. In this post, I will show you how to extend UXGridView’s editing experiences by customizing the available column types, the editing template and the editing template selector.

Defining Columns Manually

First of all, you need to set the AutoGenerateColumns property of the UXGridView control to false.

<Intersoft:UXGridView AutoGenerateColumns="False">                
</Intersoft:UXGridView>
    

Next, you specify each column manually as follows.

<Intersoft:UXGridView AutoGenerateColumns="True">
    <Intersoft:UXGridView.Columns>
        <Intersoft:UXGridViewCheckBoxColumn
            Header="Discontinued"
            Binding="{Binding Discontinued}"/>
        <Intersoft:UXGridViewComboBoxColumn 
            Header="Category ID" Width="120"
            DisplayMemberPath="CategoryName" ValueMemberPath="CategoryID" 
            Binding="{Binding CategoryID}"                                                         
            ValueListSource="{Binding Categories,
            Source={StaticResource CategoriesViewModel}}"/>
        <Intersoft:UXGridViewTextColumn 
            Header="Product ID" 
            Binding="{Binding ProductID}" 
            IsReadOnly="True"/>
        <Intersoft:UXGridViewTextColumn 
            Header="Product Name"
            Binding="{Binding ProductName}"/>
        <Intersoft:UXGridViewTextColumn 
            Header="Units In Stock" 
            Binding="{Binding UnitsInStock}"/>
        <Intersoft:UXGridViewTextColumn 
            Header="Unit Price" 
            Binding="{Binding UnitPrice}"/>
        <Intersoft:UXGridViewTextColumn 
            Header="Units On Order" 
            Binding="{Binding UnitsOnOrder}"/>
        <Intersoft:UXGridViewTextColumn 
            Header="Quantity Per Unit"
            Binding="{Binding QuantityPerUnit}"/>
    </Intersoft:UXGridView.Columns>                               
</Intersoft:UXGridView>
    

The results look like the following screenshot.

Dropdown column in UXGridView

Notice that I used three different types of column.

  • UXGridViewTextColumn

    The column has a textual representation for data display and a UXTextBox for data editing control.

  • UXGridViewCheckBoxColumn

    The column has a check box representation to display the data and a UXCheckBox for data editing control.

  • UXGridViewComboBoxColumn

    The column has a textual representation to display the data, a dropdown button to display the data list, and a UXComboBox for data editing control.

Using UXGridViewTextColumn and UXGridViewCheckBoxColumn is pretty straightforward, you just need to set the Binding and Header properties, and you’re all set. For UXGridViewComboBoxColumn, you need to specify the ValueListSource which is required for the combo box data source, along with the DisplayMemberPath and ValueMemberPath.

In this sample, I assigned the ValueListSource  for the UXGridViewComboBoxColumn from a static resource.

<Grid.Resources>
    <ViewModels:CategoriesViewModel x:Key="CategoriesViewModel"/>        
</Grid.Resources>
    

The Categories ViewModel looks like the following code.

using System.Collections.Specialized;
using Intersoft.Client.Data.ComponentModel;
using UXGridView.Samples.ModelServices;

namespace UXGridView.Samples.ViewModels
{
    public class CategoriesViewModel : ViewModelBase
    {
        public CategoriesViewModel()
        {
            this.CategoriesSource = CategoriesRepository.Instance;
            this.LoadCategories();
        }

        private INotifyCollectionChanged _Categories;

        public INotifyCollectionChanged Categories
        {
            get { return this._Categories; }
            set
            {
                if (this._Categories != value)
                {
                    this._Categories = value;
                    this.OnPropertyChanged("Categories");
                }
            }
        }

        public IDataRepository CategoriesSource { get; set; }

        public virtual void LoadCategories()
        {
            this.CategoriesSource.GetData
            (
                (Categories) =>
                {
                    this.Categories = new PagedCollectionView(Categories);
                },
                (error) =>
                {

                }
            );
        }
    }
}

    

Notice that the CategoriesViewModel simply retrieves the data from the CategoriesSource which used repository pattern for loosely-coupled data access. To learn more about data repository pattern, see the ProductsRepository example in my previous blog post.

Using Custom Editing Controls

In many business scenarios, you’re often asked to provide more advanced editing controls in the GridView rather than just a plain textbox, such as DateTimePicker, Slider, MaskedInput, etc. Luckily, it’s fairly easy to implement in UXGridView, thanks to the solid editing architecture. All you need to do is simply creating a data template that contains the input control of your choice, and assign it to the CellEditingTemplate property of the UXGridView.

The following examples show how to customize the editing control of each column through the provided CellEditingTemplate property.

<Intersoft:UXGridViewTextColumn 
    Header="Units In Stock" 
    Binding="{Binding UnitsInStock}">
    <Intersoft:UXGridViewTextColumn.CellEditingTemplate>
        <DataTemplate>
            <Intersoft:UXNumericUpDown 
                Maximum="9999" 
                Value="{Binding UnitsInStock, Mode=TwoWay}" 
                HorizontalAlignment="Stretch" 
                VerticalAlignment="Stretch"/>
        </DataTemplate>
    </Intersoft:UXGridViewTextColumn.CellEditingTemplate>
</Intersoft:UXGridViewTextColumn>

<Intersoft:UXGridViewTextColumn Header="Unit Price" Binding="{Binding UnitPrice}"> <Intersoft:UXGridViewTextColumn.CellEditingTemplate> <DataTemplate> <Intersoft:UXCurrencyEditor EditMask="c2" UseEditMaskAsDisplayMask="True" Value="{Binding UnitPrice, Mode=TwoWay}"/> </DataTemplate> </Intersoft:UXGridViewTextColumn.CellEditingTemplate> </Intersoft:UXGridViewTextColumn>
<Intersoft:UXGridViewTextColumn Header="Units On Order" Binding="{Binding UnitsOnOrder}"> <Intersoft:UXGridViewTextColumn.CellEditingTemplate> <DataTemplate> <Intersoft:UXSliderBar Value="{Binding UnitsOnOrder, Mode=TwoWay}" SmallChange="10" LargeChange="20" Maximum="100"/> </DataTemplate> </Intersoft:UXGridViewTextColumn.CellEditingTemplate> </Intersoft:UXGridViewTextColumn>

The following examples show how to use UXDateTimePicker to edit a date time column. Notice that you can bind the BirthDate to the column and directly specify the string format in the binding expression.

<Intersoft:UXGridViewTextColumn 
    Header="Birth Date" 
    Binding="{Binding BirthDate, StringFormat=MM/dd/yyyy}">
    <Intersoft:UXGridViewTextColumn.CellEditingTemplate>
        <DataTemplate>
            <Grid Background="White" Margin="1">
                <Intersoft:UXDateTimePicker 
                    Value="{Binding BirthDate, Mode=TwoWay}" 
                    EditMask="MM/dd/yyyy" 
                    BorderThickness="0"                                                              
                    UseEditMaskAsDisplayMask="True" 
                    VerticalAlignment="Center" 
                    HorizontalAlignment="Stretch"/>
            </Grid>
        </DataTemplate>
    </Intersoft:UXGridViewTextColumn.CellEditingTemplate>
</Intersoft:UXGridViewTextColumn>
<Intersoft:UXGridViewTemplateColumn Header="Address" Binding="{Binding Address}" Width="100"> <Intersoft:UXGridViewTemplateColumn.CellTemplate> <DataTemplate> <TextBlock TextWrapping="Wrap" Text="{Binding Address}" Margin="4"/> </DataTemplate> </Intersoft:UXGridViewTemplateColumn.CellTemplate> <Intersoft:UXGridViewTemplateColumn.CellEditingTemplate> <DataTemplate> <Intersoft:UXTextBox AcceptsReturn="True" TextWrapping="Wrap" Text="{Binding Address, Mode=TwoWay}"/> </DataTemplate> </Intersoft:UXGridViewTemplateColumn.CellEditingTemplate> </Intersoft:UXGridViewTemplateColumn>

As seen in the example above, UXGridView provides a template column named UXGridViewTemplateColumn. This column allows you to change both display and editing appearance. In the example, the UXGridViewTemplateColumn uses a wrapable TextBlock for the display, and a multi-line TextBox for data editing.

You can define literally any kind of input controls that support MVVM in the CellEditingTemplate, including our latest advanced input controls such as UXCalendar, UXDomainUpDown, UXDateTimeEditor, and so forth.

Using Cell Editing Template Selector

A rather unique scenario is where the users would like to have different editing control for the same column which depends on the data being edited. This can be achieved elegantly in UXGridView by using CellEditingTemplateSelector. It works similar to any other template selectors, so the first thing you need to do is creating a template selector class that derived from DataTemplateSelector.

using System.Windows;
using Intersoft.Client.Framework;
using Intersoft.Client.UI.Data;

namespace UXGridView.Samples.Selectors
{
    public class CellEditingSelector: DataTemplateSelector
    {
        public DataTemplate NumericEditor { get; set; }
        public DataTemplate SliderEditor { get; set; }

        public override DataTemplate SelectTemplate(object item, 
                 DependencyObject container)
        {            
            UXGridViewCell cell = container as UXGridViewCell;
            UXGridViewRowBase rowBase = cell.OwningRowBase;
            UXGridViewRow row = rowBase as UXGridViewRow;

            switch (cell.OwningColumn.PropertyName)
            {
                case "UnitsInStock":
                    if (rowBase.IsNewRow || (row != null && row.Index % 2 != 0))
                        return this.SliderEditor;
                    else
                        return this.NumericEditor;                    
            }

            return null;
        }
    }
}

The above code basically selects the editing control differently depending on whether the row is a normal or an alternating row. Notice that the conditioning is scoped to UnitsInStock column only.

Finally, let’s assign the template selector to the UXGridView, see the code below.

<Grid.Resources>
    <DataTemplate x:Key="NumericEditor">
        <Intersoft:UXNumericUpDown Maximum="100"
                   Value="{Binding UnitsInStock, Mode=TwoWay}"
                   HorizontalAlignment="Stretch"
                   VerticalAlignment="Stretch"/>
    </DataTemplate>
    <DataTemplate x:Key="SliderEditor">
        <Intersoft:UXSliderBar
                   Value="{Binding UnitsInStock, Mode=TwoWay}"
                   SmallChange="10" LargeChange="20" Maximum="100"/>
    </DataTemplate>
<Selectors:CellEditingSelector x:Key="CellEditingSelector" NumericEditor="{StaticResource NumericEditor}" SliderEditor="{StaticResource SliderEditor}"/> </Grid.Resources> <Intersoft:UXGridView CellEditingTemplateSelector= "{StaticResource CellEditingSelector}">

As the result, editing the cells of UnitsInStock for the normal row will show a UXNumericUpDown control. See the illustration below.

UXNumericUpDown for normal row editing

While editing the cells for the alternating row of the same column will show a UXSliderBar control instead.

UXSliderBar for alternate row editing

That’s all for now, I hope this post gives you some cool ideas on using the available column types and customizing the editing controls in UXGridView. All samples I used in this blog post are available in our latest CTP release. Click here to download it now and get yourself familiar with the MVVM implementation in the UXGridView, starting from the data retrieval, handling the data editing, to customizing editing controls.

Best Regards,

Andry

UXGridView Part 4: Data Editing the MVVM-way with Commands

In the previous post, Jimmy announced the latest CTP for UXGridView with the CUD (Create, Update and Delete) capability. In this post, I will provide the step-by-step instructions to work with these new features.

Enabling the CUD capability

First of all, let’s enable the CUD (Create, Update, Delete) capability in UXGridView. You can enable these features by simply setting the CanUserAdd, CanUserEdit, and CanUserDelete properties to True.

<Intersoft:UXGridView CanUserAdd="True" 
                      CanUserDelete="True" 
                      CanUserEdit="True"/>
        

Notice that there will be a NewRow element at the top of the Grid when you set the CanUserAdd property to True.

Furthermore, you can also delete or edit the selected item(s) when the CanUserEdit or CanUserDelete properties are set to True.

To edit a row you can use either mouse or keyboard. The following list shows you some configuration that you can change to edit a record using mouse / keyboard.

To edit a row using mouse:

  • EditMouseGesture
    • Single Click

      Directly begin edit to the current selected cell.

    • Second Click

      Begin edit to the current selected cell after the row is selected.

    • Double Click

      Directly begin edit to the current selected cell when double click fires.

To edit a row using keyboard:

  • EditKeyGEditKeyGesture
    • F2

      Directly begin edit to the current selected cell using F2 key.

    • Any Keystroke

      Directly begin edit to the current selected cell from any key stroke.

  • EnterKeyAction
    • EnterEdit

      Directly begin edit to the current selected cell using Enter key.

    • MoveToNextRow

      Move to next row (does not edit the cell).

  • EditEnterKeyAction
    • CommitAndMovetoNextRow

      Commit the changes at current edited row and move to the next row.

    • ExitEdit

      Exit the cell edit of the current edited cell.

    • MoveToNextEditableCell

      Move to next editable cell. (Will move to next row’s cell when it reach the end of the row)

Beside these options, you can also use several common keystroke as listed below during editing.

  • Tab / Shift + Tab

    To move to next / previous editable cell.

  • Shift + Enter

    Commit the changes at current edited row and stay in the current selection

  • Delete

    Delete the current selected record(s)

  • Escape

    Cancel current changes. If currently you are in an active edit cell, it will cancel the cell changes. If you are in current active edit row, it will cancel the row changes.

Handling the CUD operation

To handle the CUD operation, UXGridView provides several command-related properties that you can specify to execute a method depending on the actions. These command- properties are listed as follows:

  • PrepareNewRowCommand

    Called when you begin edit at the NewRow element. Used to initialized the NewRowItem.

  • ValidateRowCommand

    Validate the row before the row is committed.

  • InsertRowCommand

    Called when a new row is committed. You can directly save the changes and/or refresh the UXGridView if necessary.

  • UpdateCellCommand

    Called when the cell is committed.

  • UpdateRowCommand

    Called when an existing row is committed. You can directly save the changes and/or refresh the UXGridView if necessary.

  • DeleteRowCommand

    Called when a row is deleted. You can directly save the changes and / or refresh the UXGridView if necessary.

  • RejectRowCommand

    Called when the changes in the row is cancelled. This command is used to reject the changes in the data entity if required (such as in DevForce).

  • SaveChangesCommand

    Called when the save changes command is executed. You handle this command to save all the pending changes made in the UXGridView.

  • RejectChangesCommand

    Called when the reject changes command is executed. You handle this command to reject all the pending changes made in the UXGridView.

These command properties can be bound to your ViewModel using delegate command. Next, I will show you how to bind these commands along with some important properties that are necessary for the CUD operation.

Binding the CUD Commands to UXGridView using MVVM Pattern

Let’s create the ViewModel for our example. First, define the delegate commands and the required selection properties, then instantiate them in the constructor.

using System.Collections;
using Intersoft.Client.Framework;
using Intersoft.Client.Framework.Input;
using Intersoft.Client.UI.Data;
using UXGridView.Samples.ModelServices;

namespace UXGridView.Samples.ViewModels
{
    public class ServerEditingViewModel : ServerSideOperationViewModel
    {        
        public ServerEditingViewModel()
            : base()
        {            
            this.DeleteRowCommand = 
                new DelegateCommand(ExecuteDeleteRow);
            this.InsertRowCommand = 
                new DelegateCommand(ExecuteInsertRow);
            this.PrepareNewRowCommand = 
                new DelegateCommand(ExecutePrepareNewRow);
            this.UpdateCellCommand = 
                new DelegateCommand(ExecuteUpdateCell);
            this.UpdateRowCommand = 
                new DelegateCommand(ExecuteUpdateRow);
            this.RejectRowCommand = 
                new DelegateCommand(ExecuteRejectRow);
            this.RejectChangesCommand = 
                new DelegateCommand(ExecuteRejectChanges);
            this.SaveChangesCommand = 
                new DelegateCommand(ExecuteSaveChanges);
            this.ValidateRowCommand = 
                new DelegateCommand(ExecuteValidateRow);
        }

        #region Fields

        private bool _hasChanges;
        private bool _isRefreshed;        
        private object _newProduct;
        private object _selectedProduct;
        private IEnumerable _selectedProducts;

        #endregion

        #region EditableProductsSource

        private IEditableDataRepository EditableProductsSource
        {
            get
            {
                return this.ProductsSource as IEditableDataRepository;
            }
        }

        #endregion

        #region Selection and Editing Properties

        public object NewProduct
        {
            get { return this._newProduct; }
            set
            {
                if (this._newProduct != value)
                {
                    this._newProduct = value;
                    this.OnPropertyChanged("NewProduct");
                }
            }
        }

        public object SelectedProduct
        {
            get { return this._selectedProduct; }
            set
            {
                if (this._selectedProduct != value)
                {
                    this._selectedProduct = value;
                    this.OnPropertyChanged("SelectedProduct");
                }
            }
        }

        public IEnumerable SelectedProducts
        {
            get { return this._selectedProducts; }
            set
            {
                if (this._selectedProducts != value)
                {
                    this._selectedProducts = value;
                    this.OnPropertyChanged("SelectedProducts");
                }
            }
        }

        public bool IsRefreshed
        {
            get { return this._isRefreshed; }
            set
            {
                if (this._isRefreshed != value)
                {
                    this._isRefreshed = value;
                    this.OnPropertyChanged("IsRefreshed");
                }
            }
        }

        public bool HasChanges
        {
            get { return _hasChanges; }
            set
            {
                if (_hasChanges != value)
                {
                    _hasChanges = value;
                    OnPropertyChanged("HasChanges");
                }
            }
        }

        #endregion

        #region Commands

        public DelegateCommand DeleteRowCommand { get; set; }
        public DelegateCommand InsertRowCommand { get; set; }
        public DelegateCommand PrepareNewRowCommand { get; set; }
        public DelegateCommand UpdateCellCommand { get; set; }
        public DelegateCommand UpdateRowCommand { get; set; }
        public DelegateCommand RejectRowCommand { get; set; }
        public DelegateCommand RejectChangesCommand { get; set; }
        public DelegateCommand SaveChangesCommand { get; set; }
        public DelegateCommand ValidateRowCommand { get; set; }

        #endregion
    }
}
    

Next, we will bind these commands to the UXGridView.

<Intersoft:UXPage 
	xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
	xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
	xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
	mc:Ignorable="d"
	xmlns:Intersoft="http://intersoft.clientui.com/schemas"
          xmlns:IntersoftModel="clr-namespace:Intersoft.Client.Data.Component
Model.CollectionViews;assembly=Intersoft.Client.Data.ComponentModel" xmlns:ViewModels="clr-namespace:UXGridView.Samples.ViewModels" x:Class="UXGridView.Samples.Views.ServerSideOperation.Editing" Title="Editing Page" d:DesignWidth="1024" d:DesignHeight="800"> <Grid x:Name="LayoutRoot"> <Grid.DataContext> <ViewModels:ServerEditingViewModel/> </Grid.DataContext>
<Intersoft:DockPanel> <Intersoft:UXGridView AutoGenerateColumns="False" QueryOperation="Server" CanUserPage="True" PageSize="20" RowHeaderVisibility="Visible" IsBusy="{Binding IsBusy, Mode=TwoWay}" IsRefreshed="{Binding IsRefreshed, Mode=TwoWay}" ItemsSource="{Binding Products}" SortDescriptors="{Binding QueryDescriptor.SortDescriptors, Mode=TwoWay}" PageDescriptor="{Binding QueryDescriptor.PageDescriptor}" GroupFootersVisibility="Visible" GroupByBoxVisibility="Visible" CanUserAdd="true" CanUserDelete="true" CanUserEdit="true" NewItem="{Binding NewProduct, Mode=TwoWay}" SelectedItem="{Binding SelectedProduct, Mode=TwoWay}" ValidateRowCommand="{Binding ValidateRowCommand}" InsertRowCommand="{Binding InsertRowCommand}" DeleteRowCommand="{Binding DeleteRowCommand}" PrepareNewRowCommand="{Binding PrepareNewRowCommand}" UpdateCellCommand="{Binding UpdateCellCommand}" UpdateRowCommand="{Binding UpdateRowCommand}" SaveChangesCommand="{Binding SaveChangesCommand}" RejectRowCommand="{Binding RejectRowCommand}" RejectChangesCommand="{Binding RejectChangesCommand}" HasChanges="{Binding HasChanges}"> <Intersoft:UXGridView.GroupDescriptors> <Intersoft:UXGridViewGroupDescriptor PropertyName="CategoryID"/> </Intersoft:UXGridView.GroupDescriptors> <Intersoft:UXGridView.Columns> <Intersoft:UXGridViewTextColumn Header="Category ID" Binding="{Binding CategoryID}"/> <Intersoft:UXGridViewTextColumn Header="Product ID" Binding="{Binding ProductID}" IsReadOnly="True" Aggregate="Count" FooterFormatString="Count = {0}"/> <Intersoft:UXGridViewTextColumn Header="Product Name" Binding="{Binding ProductName}"/> <Intersoft:UXGridViewTextColumn Header="Units In Stock" Binding="{Binding UnitsInStock}" Aggregate="Max" FooterFormatString="Max = {0}"/> <Intersoft:UXGridViewTextColumn Header="Unit Price" Binding="{Binding UnitPrice}" Aggregate="Avg" FooterFormatString="Avg = {0:n2}"/> <Intersoft:UXGridViewTextColumn Header="Units On Order" Binding="{Binding UnitsOnOrder}" Aggregate="Min" FooterFormatString="Min = {0}"/> <Intersoft:UXGridViewTextColumn Header="Quantity Per Unit" Binding="{Binding QuantityPerUnit}"/> </Intersoft:UXGridView.Columns> </Intersoft:UXGridView> </Intersoft:DockPanel> </Grid> </Intersoft:UXPage>

Handling the CUD Operation in ViewModel Using DevForce

After the commands are bound to the ViewModel, it is up to you how you want to handle the CUD operation.

If you prefer to automatically update the records after each CUD operation, you can do that in the InsertRowCommand, UpdateRowCommand and DeleteRowCommand respectively, and probably followed up by RefreshCommand to refresh the data. However, if you prefer a batch update, you can notify the UXGridView by setting the HasChanges property to True, and later call the SaveChanges method to perform the batch update.

This batch update capability might not be available in all data providers such as WCF RIA. When you enable server query in WCF RIA such as paging, sorting, and filtering; you always get a new fresh data from the database regardless of the changes in the client. This behavior is due to the WCF RIA not supporting client-side caching. In this case, you might want to do automatic update and/or refresh after each CUD operation. There are samples that show how to do this in our CTP package.

Next, I will show you how to handle the CUD Operation in the ViewModel. To save time, I will only cover the one using DevForce which allows you to enable batch update.

Since the sample used ProductsRepository to encapsulate all data operation, I’ll show you first what I’m doing in the ProductsRepository.

using System;
using System.Collections;
using System.ComponentModel;
using IdeaBlade.EntityModel;
using IdeaBlade.Validation;
using Intersoft.Client.Data.ComponentModel;
using Intersoft.Client.Data.Provider.DevForce;
using UXGridView.Samples.Data.DevForce;

namespace UXGridView.Samples.ModelServices
{
    public class ProductsRepository : IEditableDataRepository
    {
        public ProductsRepository(NorthwindEntities entityManager)
        {
            this.Manager = entityManager;
        }

        private static IDataRepository _repository;

        public static IDataRepository Instance
        {
            get
            {
                return _repository ?? (_repository = CreateRepository());
            }
            set
            {
                _repository = value;
            }
        }

        private NorthwindEntities Manager { get; set; }

        public static IDataRepository CreateRepository()
        {
            return new ProductsRepository(EntityManager.Create());
        }

        public void GetData(Action<IEnumerable> onSuccess, 
Action<Exception> onFail) { this.Manager.Products .ExecuteAsync( op => { if (op.CompletedSuccessfully) { if (onSuccess != null) onSuccess(op.Results); } else { if (onFail != null) { op.MarkErrorAsHandled(); onFail(op.Error); } } } ); } public void GetData(QueryDescriptor queryDescriptor, Action<IEnumerable> onSuccess, Action<int> onItemCountRetrieved, Action<Exception> onFail) { this.Manager.Products.OrderBy(p => p.ProductID).Parse(queryDescriptor) .ExecuteAsync( op => { if (op.CompletedSuccessfully) { if (onSuccess != null) onSuccess(op.Results); if (onItemCountRetrieved != null) onItemCountRetrieved(-1); // not applicable; } else { if (onFail != null) { op.MarkErrorAsHandled(); onFail(op.Error); } } } ); } public void GetTotalItemCount (QueryDescriptor queryDescriptor, Action<int> onSuccess) { var op = this.Manager.Products .Parse(queryDescriptor, false).AsScalarAsync().Count(); op.Completed += (o, e) => { if (onSuccess != null) onSuccess(e.Result); }; } public void Insert(object entity) { this.Manager.AddEntity(entity); } public void Delete(IList entities) { foreach (object o in entities) { this.Delete(o); } } public void Delete(object entity) { Product product = entity as Product; product.EntityAspect.Delete(); } public void RejectChanges() { this.Manager.RejectChanges(); } public void SaveChanges( Action onSuccess, Action<Exception> onError) { this.Manager.SaveChangesAsync ( op => { if (op.IsCompleted) { if (op.HasError) { // handle error op.MarkErrorAsHandled(); onError(op.Error); } else { onSuccess(); } } }, null ); } public object Create() { return this.Manager.CreateEntity<Product>(); } public void Validate(object entity) { Product product = (Product)entity; product.EntityAspect.ValidationErrors.Clear(); product.EntityAspect.VerifierEngine.Execute(product); if (product.CategoryID < 1 || product.CategoryID > 8) product.EntityAspect.ValidationErrors .Add(new VerifierResult( VerifierResultCode.Error, "Specified CategoryID does not exist", new string[] { "CategoryID" })); if (product.UnitPrice < 0) product.EntityAspect.ValidationErrors .Add(new VerifierResult (VerifierResultCode.Error, "Unit Price can not be less than 0", new string[] { "UnitPrice" })); if (product.UnitsInStock < 0) product.EntityAspect.ValidationErrors .Add(new VerifierResult( VerifierResultCode.Error, "Units in Stock can not be less than 0", new string[] { "UnitsInStock" })); if (product.UnitsOnOrder < 0) product.EntityAspect.ValidationErrors .Add(new VerifierResult( VerifierResultCode.Error, "Units on Order can not be less than 0", new string[] { "UnitsOnOrder" })); } public void RejectChanges(object entity) { IRevertibleChangeTracking revertible =
(IRevertibleChangeTracking)entity;
revertible.RejectChanges(); } } }

Finally, let’s handle the CUD commands in our ViewModel.

For Create Operation

public void ExecuteInsertRow(object parameter)
{
    this.NewProduct = null;

    if (!this.IsBatchUpdate)
        this.SaveChanges();
    else
        this.HasChanges = true;
}

public void ExecutePrepareNewRow(object parameter)
{

    // It's possible to initialize the new row with default values
    // Example:
    // product.ProductName = "New Product";

    this.NewProduct = this.EditableProductsSource.Create();
    this.EditableProductsSource.Insert(this.NewProduct);
}
    

For Update Operation

public void ExecuteUpdateCell(object parameter)
{
    object[] updateCellParameters = (object[])parameter;
    object product = updateCellParameters.GetValue(0);
    string property = updateCellParameters.GetValue(1).ToString();

    // perform cell-level validation if required
}

public void ExecuteUpdateRow(object parameter)
{
    if (!this.IsBatchUpdate)
        this.SaveChanges();
    else
        this.HasChanges = true;
}

For Delete Operation

public void ExecuteDeleteRow(object parameter)
{
    this.EditableProductsSource.Delete(parameter as IList);

    if (!this.IsBatchUpdate)
        this.SaveChanges();
    else
        this.HasChanges = true;
}

For Validation, Reject Row and Refresh Operation

public void SaveChanges()
{
    this.IsBusy = true;

    this.EditableProductsSource.SaveChanges
    (
        () =>
        {
            this.IsRefreshed = true;
            this.LoadProducts(); // refresh
            this.HasChanges = false;
            this.IsBusy = false;
        },
        exception =>
        {
            this.IsBusy = false;

            MessagePresenter presenter = new MessagePresenter();
            presenter.ShowErrorMessage("An unexpected error has occurred: " 
+ exception.Message); } ); } public void ExecuteValidateRow(object parameter) { this.EditableProductsSource.Validate(parameter); } public void ExecuteRejectRow(object parameter) { if (parameter != null) this.EditableProductsSource.RejectChanges(parameter); this.NewProduct = null; }

For Batch Operation

public void ExecuteRejectChanges(object parameter)
{
    this.EditableProductsSource.RejectChanges();
    this.HasChanges = false;
}

public void ExecuteSaveChanges(object parameter)
{
    // if users click on the save changes while the new row is being edited,
    // presume the new row isn't intended
    if (this.NewProduct != null)
        this.EditableProductsSource.RejectChanges(this.NewProduct);

    this.SaveChanges();
}

I hope this post gives you a comprehensive understanding on handling the CUD (Create, Update, Delete) operation in UXGridView using MVVM design pattern. In the next post, I will blog about customizing editing controls in UXGridView, for instance, customizing the editing control of certain columns to more advanced input controls such as UXDateTimePicker, UXNumericUpDown, UXSliderBar, and so forth.

If you have any questions regarding the CUD operation, please post some questions in our community website.

Regards,

Andry

UXGridView CTP2: MVVM Data Editing

Two weeks ago, we released the first CTP of our new data controls for Silverlight and WPF. The first CTP was focused on MVVM Grid architecture and server-based data access, as well as data operation such as paging and filtering. More information can be found here.

Today, I’m excited to announce the availability of the second CTP of our data controls. Our milestone in this release is strongly focused on data validation and data editing that supports MVVM design pattern. The release also includes a number of great features like batch update support for DevForce data service, native ValueList support for display and edit mode, customizable editing controls, and a host of UI/X tweaking.

Click here to download the CTP2, and read the details below to discover what’s new.

Data Validation & Editing with MVVM Pattern

For decades, developers have to write a bunch of code to implement an editable grid, from wiring editing events to writing validation code in a number of places. That’s even true for the latest built-in Silverlight DataGrid, for instances, you should write code to perform data validation in the RowEditEnded event. This pattern of development, unfortunately, makes your code difficult to test and maintain. And it definitely violates the MVVM pattern as the event wiring requires a strong reference to the view elements.

Unlike other Silverlight grids, UXGridView supports MVVM-style data editing out-of-the-box. It allows you to write data validation and editing logic entirely in the ViewModel without trading-off the rich editing features in the grid. The benefits of using MVVM in data editing applications are obvious – you can easily reuse, test and extend the interactions logics in the ViewModel without affecting the view or data access layers.

With UXGridView, you don’t wire events in order to perform data validation. While we still provided routed events as a mean to work with the Grid using the classic MVP pattern, it’s unnecessary to wire any editing events to perform editing operations such as begin, commit or cancel edit. Implementing data validation and editing using MVVM pattern is simple and straightforward. First, you create the delegate commands for each editing command in the ViewModel, then bind the commands to the UXGridView through data binding declaration.

The following illustration shows a simple MVVM implementation of data validation and editing in UXGridView.

ViewModel:

 public DelegateCommand DeleteRowCommand { get; set; }
 public DelegateCommand InsertRowCommand { get; set; }
 public DelegateCommand UpdateRowCommand { get; set; }
 public DelegateCommand ValidateRowCommand { get; set; }

 public void ExecuteValidateRow(object parameter)
 {
      this.EditableProductsSource.Validate(parameter);
 }

public void ExecutePrepareNewRow(object parameter)
{
    this.NewProduct = this.EditableProductsSource.Create();
    this.EditableProductsSource.Insert(this.NewProduct);
}

public void ExecuteDeleteRow(object parameter)
{
    this.EditableProductsSource.Delete(parameter as IList);
}

 ...

XAML Page:

 <Intersoft:UXGridView ItemsSource="{Binding Products}" 
              CanUserAdd="True" 
              CanUserDelete="True"
              CanUserEdit="True"
              SelectedItem="{Binding SelectedProduct, Mode=TwoWay}"
              ValidateRowCommand="{Binding ValidateRowCommand}"
              InsertRowCommand="{Binding InsertRowCommand}"
              DeleteRowCommand="{Binding DeleteRowCommand}"
              UpdateRowCommand="{Binding UpdateRowCommand}" />

As you can see from the above code snippet, the beautiful of the MVVM pattern is that you have full control over your business and interaction logic. For example, if you used a powerful data service like DevForce, you can simply delegate the call to a repository that automatically execute the validation to the given entity.

You really don’t need to worry about the change tracking, dirty state, or valid state – the UXGridView takes care of them automatically. For an instance, when the modified row contains validation errors, UXGridView will not allow you to commit the changes until you correct the error, or cancel the changes – see the screenshot below.

Intuitive row validation

In addition to the solid MVVM-ready editing architecture, UXGridView also sports great looking interface, which includes a handy error message displayed in the status bar, as well as error notification in the row and row header.

New Row & Delete

You asked for it, we deliver! The new UXGridView brings back the features you loved to use such as the “new row” interface for quick data adding, inline editing, and delete row support. While these features sound common in most ASP.NET grids, they aren’t in Silverlight, so we built one.

The "new row” interface works pretty much similar to the ASP.NET version of our flagship WebGrid. You click on the new row bar to begin adding new rows. Keyboard arrow keys are also fully supported for navigating to the new row.

New row interface

The other nice feature is the support for multiple selection and row delete. The multiple selection is enabled by default, so you can easily select multiple rows by using the combination of Ctrl and Shift keys. Once selected, press Delete to delete the selection.

Multiple selection

Batch Update Support for DevForce

If you noticed on the above screenshots close enough, chances are that you’ll spot two interesting buttons beside the pager control. Think you’ve seen these buttons before? Well, you must have seen it in the batch update feature we implemented in the ASP.NET version of our WebGrid.

If you haven’t heard much about batch update, it is a very powerful feature in data-aware applications which allows you to make multiple edits locally and submit them in a single round trip. Unfortunately, the batch update implementation in Silverlight is fairly challenging since the UXGridView control should not be tightly coupled to any data access strategy. This means that the batch update should be supported by the data service provider as well.

Luckily, DevForce from IdeaBlade includes full support for batch update, thanks to their client-side caching feature. The WCF RIA Services, on the other hands, has very limited support for batch update, you might notice the options to be disabled in several editing samples for RIA.

When the batch update feature is enabled, all changes you made in the UXGridView will be kept locally. Consequently, your implementation for the Insert, Update and Delete in the ViewModel is not required to call the Save method. This, and many other benefits, make batch update an ideal approach to your data intensive applications as data input becomes more responsive and faster with reduced server-client round trip.

The changes you made in the grid can be submitted to server in batch through the SaveChanges command; or rejected through the RejectChanges command. The UXGridView control provides default buttons in the status bar interface which execute these commands, see the illustration below.

Batch update commands

The SaveChanges and RejectChanges commands will be automatically disabled when they cannot execute. For instances, when the grid is busy, or when the grid has no more changes. Again, this process is controlled from your ViewModel through the binding to the HasChanges property in UXGridView.

You can also explore a bunch of editing behaviors implemented in the UXGridView. In the DevForce samples, you can try to use inline or batch update mode via the Options panel, see below.

Sample options

Customizable Editing Controls

Now that we’ve got MVVM-ready editing architecture covered, as well as the editing behaviors like the enter key action and edit mouse gesture, the CTP2 release also shipped with powerful editing architecture that you’ll definitely excited to see.

Unlike other grid controls that require you to write specific interface to properly work in editing mode, we introduced editing cell template that allows you to use any existing input controls as the editing control for that specific column.

One of my favorite features is the easy plug-in to use the advanced input controls we introduced in the previous release such as UXNumericUpDown, UXDateTimePicker, UXCurrencyEdit and UXSliderBar just to name a few. For an instance, the following code shows how to use the UXNumericUpDown control as the editing control for UnitsInStock column:

 <Intersoft:UXGridViewTextColumn Header="Units In Stock"
                                 Binding="{Binding UnitsInStock}">
     <Intersoft:UXGridViewTextColumn.CellEditingTemplate>
         <DataTemplate>
             <Intersoft:UXNumericUpDown Maximum="9999" 
                        Value="{Binding UnitsInStock, Mode=TwoWay}"/>
         </DataTemplate>
     </Intersoft:UXGridViewTextColumn.CellEditingTemplate>
 </Intersoft:UXGridViewTextColumn>

Using UXNumericUpDown as editing control

You can also use a more unique, non-textbox input control such as UXSliderBar, by simply defining the control in the CellEditingTemplate similar to the above example.

Using UXSliderBar as editing control

The release also includes many other exciting features such as native ValueList support on both cell and editing mode, column template, and editing template selector. More on these in the next post.

Download the CTP2 Bits

Click here to download the CTP2 and test-drive the new UXGridView features today. The download package includes latest ClientUI assemblies as well as updated and new samples for both Silverlight and WPF platforms.

Make sure you checked out the new samples shipped in this CTP2 release, see the red-highlighted sections below.

New samples

Enjoy the new CTP bits! In the next several posts, we will cover more code-level details and usages on the UXGridView related to the editing features, so stay tuned.

We’d love to hear what you think about the new features available in CTP2, please post your feedback, questions or issues to our community forum.

All the best,

Jimmy

UXGridView Part 3: Fundamental Grid Features

The core feature-sets that we wanted to focus in the first data controls CTP are the QueryDescriptor component model, and the fundamental grid architecture/features such as high-performance virtualization, adaptable layout, drag and drop, grouping and much more. In my previous post, I’ve explained how to use QueryDescriptor which greatly simplify server data access using MVVM design pattern. Now, I will share some of the fundamental grid features that already available in the first CTP, and what you can expect in the next release.

Virtualization

One of the most fundamental features in UXGridView is its high-performance virtualization (virtual rendering) architecture. This means that the UXGridView doesn’t actually render all the data passed to it. Instead, it implements a smart logic which virtually render the data based on the available view port and the current scroll position. This virtualization feature is applied to all types of cells and rows rendering including the RowGroupHeader and RowGroupFooter, so that you can expect a blazing fast and scalable grid control for your applications.

You can try to bind the UXGridView with an unbound collection that holds million of rows as follows.

public class Data
{
    public string Column1 { get; set; }
    public string Column2 { get; set; }
    public string Column3 { get; set; }
    public string Column4 { get; set; }
    public string Column5 { get; set; }
    public string Column6 { get; set; }
    public string Column7 { get; set; }
    public string Column8 { get; set; }
    public string Column9 { get; set; }
    public string Column10 { get; set; }
    public string Column11 { get; set; }
    public string Column12 { get; set; }
    public string Column13 { get; set; }
    public string Column14 { get; set; }
    public string Column15 { get; set; }
    public string Column16 { get; set; }
    public string Column17 { get; set; }
    public string Column18 { get; set; }
    public string Column19 { get; set; }
    public string Column20 { get; set; }
    public string Column21 { get; set; }
    public string Column22 { get; set; }
    public string Column23 { get; set; }
    public string Column24 { get; set; }
    public string Column25 { get; set; }
    public string Column26 { get; set; }
    public string Column27 { get; set; }
    public string Column28 { get; set; }
    public string Column29 { get; set; }
    public string Column30 { get; set; }
}

public partial class SilverlightControl1 : UserControl
{
    public SilverlightControl1()
    {
        InitializeComponent();

        ObservableCollection
 data = new ObservableCollection();
        for (int i = 0; i < 1000000; i++)
        {
            Data d = new Data()
            {
                Column1 = "Data1",
                Column2 = "Data2",
                Column3 = "Data3",
                Column4 = "Data4",
                Column5 = "Data5",
                Column6 = "Data6",
                Column7 = "Data7",
                Column8 = "Data8",
                Column9 = "Data9",
                Column10 = "Data10",
                Column11 = "Data11",
                Column12 = "Data12",
                Column13 = "Data13",
                Column14 = "Data14",
                Column15 = "Data15",
                Column16 = "Data16",
                Column17 = "Data17",
                Column18 = "Data18",
                Column19 = "Data19",
                Column20 = "Data20",
                Column21 = "Data21",
                Column22 = "Data22",
                Column23 = "Data24",
                Column24 = "Data25",
                Column25 = "Data25",
                Column26 = "Data26",
                Column27 = "Data27",
                Column28 = "Data28",
                Column29 = "Data29",
                Column30 = "Data30"
            };

            data.Add(d);
        }

        this.uXGridView1.ItemsSource = data;
    }
}
        

Notice that the overall UXGridView performance is based on the view port, the smaller the view port the less objects need to be rendered, thus it will perform faster.

Adaptable Layout (Dynamic Row Height)

Since rows and cells can be represented in many ways, we included a nice feature to support dynamic row height in the virtualization logic. This feature enables you to use a wrapped textblock for the cell, or using a fluid template for the Row and RowDetail without compromising the virtualization feature. Several examples of this feature were already available in the downloadable CTP that you can play around.

To enable text wrapping in the cell, right now you need to customize the CellStyle and add a TextBlock with TextWrapping property enabled. In the next release, we will add a built-in property directly in the UXGridViewColumn to easily enable text wrapping.

Drag and Drop (Column and Group Reordering)

Drag-drop interaction is commonly found in a number of Grid operations such as column reordering, and group manipulation like adding group, removing group or reordering group. Thanks to ClientUI’s robust DragDrop Framework, we can quickly provide fluid drag-drop capabilities in the UXGridView. You can find more exciting UX features related to the drag-drop in the next and third milestone of the CTP release.

Data Grouping

If you are wondering why GroupDescriptors is not included in the QueryDescriptor, it’s because data grouping is considered to be a client operation rather than a server operation. To group a data in runtime, you drag a column header and drop it onto the GroupByBox element which you can enable through the GroupByBoxVisibility property.

You can also add some predefined group declaratively as follows.

<Intersoft:UXGridView Name="uXGridView1" GroupByBoxVisibility="Visible">                        
    <Intersoft:UXGridView.GroupDescriptors>
        <Intersoft:UXGridViewGroupDescriptor PropertyName="CategoryID"/>
        <Intersoft:UXGridViewGroupDescriptor PropertyName="SupplierID"/>
    </Intersoft:UXGridView.GroupDescriptors>                                    
</Intersoft:UXGridView>

Group Total and Aggregates

In addition to the data grouping, we also introduced GroupFooter which represent the aggregate values of a specific column for a specific group. There are five built-in aggregates supported in UXGridView which are: Average, Sum, Count, Min and Max. A more advanced, customized aggregate function is also planned in the next CTP release, which leverage the use of MVVM and multi-binding.

The following example shows how to enable the group footers, and specify the aggregate function for certain columns.

<Intersoft:UXGridView Name="uXGridView1" GroupByBoxVisibility="Visible"
                        GroupFootersVisibility="Visible">                        
    <Intersoft:UXGridView.GroupDescriptors>
        <Intersoft:UXGridViewGroupDescriptor PropertyName="CategoryID"/>
        <Intersoft:UXGridViewGroupDescriptor PropertyName="SupplierID"/>
    </Intersoft:UXGridView.GroupDescriptors>                    
    <Intersoft:UXGridView.Columns>
        <Intersoft:UXGridViewTextColumn 
            Binding="{Binding Path=ProductID}" 
            Header="Product ID" />
        <Intersoft:UXGridViewTextColumn 
            Binding="{Binding Path=CategoryID}" 
            Header="Category ID"/>
        <Intersoft:UXGridViewTextColumn 
            Binding="{Binding Path=SupplierID}"
            Header="Supplier ID"/>
        <Intersoft:UXGridViewTextColumn 
            Binding="{Binding Path=ProductName}" 
            Header="Product Name"/>
        <Intersoft:UXGridViewTextColumn 
            Binding="{Binding Path=UnitPrice}" 
            Header="Unit Price" Aggregate="Avg"/>
        <Intersoft:UXGridViewTextColumn 
            Binding="{Binding Path=UnitsInStock}" 
            Header="Units In Stock" Aggregate="Sum"/>
        <Intersoft:UXGridViewTextColumn 
            Binding="{Binding Path=UnitsOnOrder}" 
            Header="Units On Order" Aggregate="Count"/>
    </Intersoft:UXGridView.Columns>
</Intersoft:UXGridView>

Upcoming UXGridView Features

In this post, you have learned some of the fundamental features available in UXGridView, such as virtualization, grouping, adaptable layout and drag-drop. We are currently topping off the rest of the features expected to ship in the CTP2 release due next week. One of the most exciting features is the unique data editing capability leveraging sophisticated custom editor concept and commanding. This will allow you to easily updating your data to the repository using MVVM design pattern. Stay tuned for our next announcement!

Best Regards,

Andry

UXGridView Part II: Data Access the MVVM-way with QueryDescriptor

As Jimmy wrote in his blog post, our upcoming Grid control for Silverlight and WPF, UXGridView, allows you to perform data operation with MVVM pattern elegantly using QueryDescriptor. In this post, I will explain some of fundamental concepts of the QueryDescriptor in more practical ways.

Understanding QueryDescriptor

First let’s take a look the QueryDescriptor class below.

QueryDescriptor Class

As you can see, the QueryDescriptor has three properties that hold the information about the query. It also has a QueryChanged event that will be raised when any of the QueryDescriptor’s properties are changed. The following illustration shows some examples on how query information is stored in the QueryDescriptor.

QueryDescriptor queryDescriptor = new QueryDescriptor();

// filtering
// get records that have 
// (UnitPrice >= 0 AND UnitPrice < 50) OR (UnitPrice == 0)
CompositeFilterDescriptorCollection groupFilter1 = 
    new CompositeFilterDescriptorCollection();

groupFilter1.LogicalOperator = FilterCompositionLogicalOperator.And;
groupFilter1.Add(
    new FilterDescriptor() 
    { 
        PropertyName = "UnitPrice", 
        Operator = FilterOperator.IsGreaterThanOrEqualTo, Value = 0 
    }
);
groupFilter1.Add(
    new FilterDescriptor() 
    { 
        PropertyName = "UnitPrice", 
        Operator = FilterOperator.IsLessThan, Value = 50 
    }
);

CompositeFilterDescriptorCollection groupFilter2 = 
    new CompositeFilterDescriptorCollection();

groupFilter2.LogicalOperator = FilterCompositionLogicalOperator.And;
groupFilter2.Add(
    new FilterDescriptor() 
    { 
        PropertyName = "UnitsInStock", 
        Operator = FilterOperator.IsEqualTo, Value = 0 
    }
);

queryDescriptor.FilterDescriptors.LogicalOperator = 
    FilterCompositionLogicalOperator.Or;

queryDescriptor.FilterDescriptors.Add(groupFilter1);
queryDescriptor.FilterDescriptors.Add(groupFilter2);

// paging
// get the record 6 - 10
queryDescriptor.PageDescriptor.PageSize = 5;
queryDescriptor.PageDescriptor.PageIndex = 1;

// sorting
// sort by category ascending then by product id descending
queryDescriptor.SortDescriptors.Add(
    new SortDescriptor() 
    { 
        PropertyName = "CategoryID", 
        Direction = System.ComponentModel.ListSortDirection.Ascending 
    }
);
queryDescriptor.SortDescriptors.Add(
    new SortDescriptor() 
    { 
        PropertyName = "ProductID", 
        Direction = System.ComponentModel.ListSortDirection.Descending 
    }
);    

With our data controls, the QueryDescriptor will be updated automatically whenever users perform data operations through our data controls such as paging, filtering and sorting. So all you need to do here is simply wiring up the QueryDescriptor to the data controls and listen to its QueryChanged event.

In the QueryChanged function delegate, you will need to parse the information in QueryDescriptor to a data operation command for your specific data source. Fortunately, our data provider libraries come with some methods allowing you to easily parse the QueryDescriptor into WCF RIA or DevForce data service.

Next, I will show you how to bind the QueryDescriptor to UXGridView, listen to its QueryChanged and perform the data operation.

Binding QueryDescriptor to UXGridView using MVVM Pattern

First, let’s create the ViewModel for our example.

using System.Collections.Specialized;
using Intersoft.Client.Data.ComponentModel;

namespace UXGridView.Samples.ViewModels
{
    public class ListProductsViewModel : ViewModelBase
    {
        public ListProductsViewModel()
        {
            this._queryDescriptor = new QueryDescriptor();
        }

        private INotifyCollectionChanged _products;
        private QueryDescriptor _queryDescriptor;

        public INotifyCollectionChanged Products
        {
            get { return this._products; }
            set
            {
                if (this._products != value)
                {
                    this._products = value;
                    this.OnPropertyChanged("Products");
                }
            }
        }

        public QueryDescriptor QueryDescriptor
        {
            get
            {
                return this._queryDescriptor;
            }
            set
            {
                if (this._queryDescriptor != value)
                {
                    if (this._queryDescriptor != null)
                        this._queryDescriptor.QueryChanged 
                            -= new System.EventHandler(OnQueryChanged);

                    this._queryDescriptor = value;
                    this._queryDescriptor.QueryChanged 
                        += new System.EventHandler(OnQueryChanged);

                    this.OnPropertyChanged("QueryDescriptor");
                }
            }
        }

        public virtual void LoadProducts()
        {

        }

        private void OnQueryChanged(object sender, System.EventArgs e)
        {
            this.LoadProducts();
        }
    }
}        

Notice that the LoadProducts() is still empty now, we’ll get to that later. Next we will bind this to our UXGridView in our View.

<Intersoft:UXPage
	xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
	xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
	xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
	mc:Ignorable="d"
	xmlns:Intersoft="http://intersoft.clientui.com/schemas"
        xmlns:ViewModels="clr-namespace:UXGridView.Samples.ViewModels"
	x:Class="UXGridView.Samples.Views.UXGridView.ListProducts"
	Title="ListProducts Page"
	d:DesignWidth="640" d:DesignHeight="480">

    <Grid x:Name="LayoutRoot">
        <Grid.DataContext>
            <ViewModels:ListProductsViewModel/>
        </Grid.DataContext>

        <Grid MaxWidth="700" Margin="12">
            <Intersoft:UXGridView 
                Margin="8" AutoGenerateColumns="False" 
                ItemsSource="{Binding Products}"
                QueryOperation="Server"
                SortDescriptors="{Binding QueryDescriptor.SortDescriptors}"
                PageDescriptor="{Binding QueryDescriptor.PageDescriptor}" 
                PageSize="20" CanUserPage="True">
                <Intersoft:UXGridView.Columns>
                    <Intersoft:UXGridViewTextColumn 
                        Header="Category ID" 
                        Binding="{Binding CategoryID}"/>
                    <Intersoft:UXGridViewTextColumn 
                        Header="Product ID" 
                        Binding="{Binding ProductID}" 
                        Aggregate="Count" FooterFormatString="Count = {0}"/>
                    <Intersoft:UXGridViewTextColumn 
                        Header="Product Name" 
                        Binding="{Binding ProductName}"/>
                    <Intersoft:UXGridViewTextColumn 
                        Header="Unit Price" 
                        Binding="{Binding UnitPrice}" 
                        Aggregate="Avg" FooterFormatString="Avg = {0}"/>
                    <Intersoft:UXGridViewTextColumn 
                        Header="Units In Stock" 
                        Binding="{Binding UnitsInStock}" 
                        Aggregate="Max" FooterFormatString="Max = {0}"/>
                    <Intersoft:UXGridViewTextColumn 
                        Header="Units On Order" 
                        Binding="{Binding UnitsOnOrder}" 
                        Aggregate="Min" FooterFormatString="Min = {0}"/>
                    <Intersoft:UXGridViewTextColumn 
                        Header="Quantity Per Unit" 
                        Binding="{Binding QuantityPerUnit}"/>
                </Intersoft:UXGridView.Columns>
            </Intersoft:UXGridView>
        </Grid>
    </Grid>
</Intersoft:UXPage>

Note that you will need to set the QueryOperation to Server to enable server-side data operation. That’s required because UXGridView also has the capability to manipulate the data at client side, which is the default setting. For now, let’s focus on the server-side query mode.

The QueryChanged event of the QueryDescriptor will be raised when it is bind to any of our data controls such as UXGridView, UXDataFilter or UXDataPager. The event will also be raised whenever there are changes in the QueryDescriptor, so it is the only place where you want to handle all data operations.

Now, let’s start processing this QueryDescriptor and retrieve a piece of data from our repository.

Parsing QueryDescriptor and Retrieving Data from WCF RIA

To parse the QueryDescriptor to WCF RIA, you need to include the Intersoft.Client.Data.Provider.Ria assembly in your project. This data provider assembly provides several methods that will allow you to easily parse the QueryDescriptor to the WCF RIA data service.

Now, let’s parse our QueryDescriptor and write some code to load the data in the LoadProducts() method that we’ve prepared in the previous section.

private NorthwindDomainContext _manager;
private NorthwindDomainContext Manager
{
    get
    {
        if (this._manager == null)
            this._manager = new NorthwindDomainContext();

        return this._manager;
    }
}

public virtual void LoadProducts()
{
    if (Intersoft.Client.Framework.ISControl.IsInDesignModeStatic)
        return;


    var query = this.Manager.GetProductsQuery()
                         .OrderBy(p => p.ProductID)
                         .Parse(this.QueryDescriptor);
    query.IncludeTotalCount = true;


    this.Manager.Load(
        query,
        op =>
        {
            if (op.IsComplete)
            {
                this.Products = new PagedCollectionView(op.Entities);
                if (op.TotalEntityCount != -1)
                    this.QueryDescriptor.PageDescriptor.TotalItemCount 
                        = op.TotalEntityCount;
            }
            else
            {
                // error handling
            }
        },

        true);
}

private void OnQueryChanged(object sender, System.EventArgs e)
{
    this.LoadProducts();
}
        

As you can see, the implementation is very straightforward, you just need to call .Parse(this.QueryDescriptor) to produce a query that WCF RIA can process. Note that IncludeTotalCount is set to True, which is important in paging scenarios as we will need to set the QueryDescriptor.PageDescriptor.TotalItemCount property to the total entity count of the particular query. This enables the data pager UI to determine the total number of pages available.

Parsing QueryDescriptor and Retrieving Data from Dev Force

In addition to the WCF RIA, you can also parse the QueryDescriptor to a DevForce service using similar approaches, with minor adjustments. First, you need to include the Intersoft.Client.Data.Provider.DevForce assembly in your project. This data provider provides similar methods as available in the RIA counterpart. Next, you need to adjust some of the code such as declaring the relavant DevForce type, see below.

private NorthwindEntities _manager;
private NorthwindEntities Manager
{
    get
    {
        if (this._manager == null)
            this._manager = new NorthwindEntities();

        return this._manager;
    }
}

public virtual void LoadProducts()
{
    if (Intersoft.Client.Framework.ISControl.IsInDesignModeStatic)
        return;

    this.Manager.Products
        .OrderBy(p => p.ProductID).Parse(this.QueryDescriptor)
        .ExecuteAsync(
        op =>
        {
            if (op.CompletedSuccessfully)
            {
                this.Products = new PagedCollectionView(op.Results);
            }
            else
            {
                // error handling
            }
        }
        );                 
}

public virtual void GetTotalItemCount()
{
    var queryCount = this.Manager.Products
        .Parse(this.QueryDescriptor, false).AsScalarAsync().Count();

    queryCount.Completed += (o, e) =>
    {
        if (e.Result != -1)
            this.QueryDescriptor.PageDescriptor.TotalItemCount = 
                e.Result;
    };    
}

private void OnQueryChanged(object sender, System.EventArgs e)
{
    this.GetTotalItemCount();
    this.LoadProducts();
}

Notice that you need to retrieve the total item count in two separate calls. This is required since DevForce handles the total item count retrieval differently.

I hope you agree that the QueryDescriptor makes MVVM and data service significantly easier and straightforward to implement. Also, remember that the QueryDescriptor can be shared across multiple controls such as UXDataFilter and UXDataPager, in addition to the UXGridView.

In my next post, I will cover about some nice Grid features that we shipped in the first CTP release. For now, download the CTP1 bits here, and enjoy building your data-centric application the MVVM way.

Best Regards,

Andry