Getting started with Metro Elements: Chart controls

Not long ago we released the beta version of Metro Elements – a suite of controls for WinRT. Currently we provide a set of powerful charting controls and a date-time picker with flexible formatting. We also have many more controls currently under development which will be released throughout the next couple of months. In this blog post I’m going to walk you though getting started with using Metro Elements. In particular, we will look at adding a couple of charts to an application and populate them with data. If you would like to follow along but don’t have the beta yet, you can download it for free from here.

Step 1: Start a new project

After you’ve installed the Metro Elements beta, run up Visual Studio 2012 and create a new blank windows store project. Next, in the Solution Explorer, right click References to add a new reference. This will popup the Reference Manager dialog. In the left pane of the dialog, navigate to Windows -> Extensions. This will bring up a list of extension SDKs. Check Metro Elements and then click OK.

Add Metro Elements SDK

Step 2 : Add the xml namespace

Next we need to add the xml namespace definition to MainPage.xaml which is where we will be placing the charts. Metro Elements has 2 namespaces. All the charting controls can be found in Mindscape.MetroElements.Charting, and everything else is in Mindscape.MetroElements. Open MainPage.xaml and add the xml namespace like this:

xmlns:ch="using:Mindscape.MetroElements.Charting"

Step 3: Adding a bar chart

Now we add a Chart control to MainPage.xaml and set it up to display a bar series. As you can see below, this is incredibly simple!

<ch:Chart Title="Bar Chart">
  <ch:BarSeries ItemsSource="{Binding Data1}" />
</ch:Chart>

Here you can see the ItemsSource of the bar series is binding to a property on the DataContext of the page. To keep things simple for this tutorial, I’ve set the DataContext to be the page itself. (Normally you would create a new model class and set the DataContext to be an instance of that). Below is the code you can add to MainPage.xaml.cs for populating the chart data:

public sealed partial class MainPage : Page
{
  private readonly Random _random = new Random();
 
  public MainPage()
  {
    this.InitializeComponent();
 
    string[] games = { "Chess", "Checkers", "Battleship", "Monopoly", "Poker", "Lawn Bowls" };
    Data1 = new List<object>();
    foreach (string s in games)
    {
      Data1.Add(new StringDouble(s, _random.NextDouble() * 30));
    }
 
    DataContext = this;
  }
 
  public IList Data1 { get; set; }
 
  protected override void OnNavigatedTo(NavigationEventArgs e)
  {
  }
}

Each object added to the items source will represent a rendered data point on the chart. For example, if you fill the chart with .NET Point objects, the chart will automatically plot the X and Y values along the appropriate axes. Metro Elements comes with various classes that you can use as data points which map strings or date times on one axis to numeric values on the other axis. You can also provide your own custom objects and tell the chart which property to plot along each axis. As you can see in the code above, I am populating the items source with StringDouble objects. Each StringDouble will be rendered as a bar on the chart and displays the string value on the X axis. Here is an example of what this produces.

Bar Chart

Step 4: Adding more bar series to the same chart

In 3 easy steps you have already set up a bar chart to display data in an application. Now I want to point out how you can add more data series to a single chart control. Metro Elements currently provides 16 different types of series that can be displayed by the Chart control. This includes bar series, line series, area series, spline series, stock series, various stacked series and more. You can plot multiple series on the same pair of X/Y axes simply by adding more data series between the Chart tags. For this tutorial, lets add another 2 bar series to the chart. Each series has its own items source, so you’ll need to add another 2 collection properties to the page for binding to. Below is the xaml code for displaying multiple bar series. Here you can see I’ve also set the SeriesBrush properties to color each bar series differently, and I’ve set the Title properties to display a name for each series in the legend.

<ch:Chart Title="Victory Chart">
  <ch:BarSeries ItemsSource="{Binding Data1}" SeriesBrush="#EAC320" Title="Matt" />
  <ch:BarSeries ItemsSource="{Binding Data2}" SeriesBrush="#ED3A8E" Title="Steve" />
  <ch:BarSeries ItemsSource="{Binding Data3}" SeriesBrush="#27A8E1" Title="Jeff" />
</ch:Chart>

Multiple bar series

Step 5: Adding a pie chart

So far I’ve showed you how to get started with adding cartesian (X/Y) charts to your application. To finish off this tutorial, let’s look at adding a pie chart. Since pie charts aren’t rendered on an X/Y plane, you plot pie charts using the PieChart control. Just like with the Chart control, you add series between the start and end tags of the control. The only series that the PieChart control accepts is the PieSeries, but by simply setting the DoughnutScale property, you can get a doughnut chart. Here is some example code:

<ch:PieChart Title="Percentage Played">
  <ch:PieSeries ItemsSource="{Binding Data4}" DoughnutScale="0.5">
    <ch:PieSeries.Brushes>
      <SolidColorBrush Color="#D9DE1F" />
      <SolidColorBrush Color="#FFCC00" />
      <SolidColorBrush Color="#A41368" />
      <SolidColorBrush Color="#C2609A" />
      <SolidColorBrush Color="#3BB2E4" />
      <SolidColorBrush Color="#9ED9F0" />
    </ch:PieSeries.Brushes>
  </ch:PieSeries>
</ch:PieChart>

Unlike the X/Y charts, each data point in a single pie series can have it’s own color and a spot in the legend. Rather than providing a single series-brush, you can provide a collection of brushes as seen above which will sequentially be applied to the data points. The best way to add data to a pie series is by using instances of the StringDouble class that I described earlier. The double value is automatically used to determine the size of each data point, and the string value appears in the legend. Of course the pie chart also supports other types of data such as your own custom model objects and you can specify the bindings that get the data and legend titles.

Pie Chart

And that’s everything you need to know to quickly get started with using our metro chart controls. When you installed Metro Elements, a shortcut to a Visual Studio samples solution would have been added to your desktop. The QuickStart project covers the topics that I’ve mentioned today, so it is a good source for further code examples. The chart controls have many features that let you customize the look and feel of the charts which I’ll talk about later.

If you have any queries about how to use any of the controls in Metro Elements, ask away in the forum. If you have any feature or control requests, we’d love to here them in the Think Tank. Also, if you’d like me to write about a particular topic related to Metro Elements, leave a comment on this blog post.

Silverlight Spell Checker

One of the controls in our Silverlight Elements control suite is the HTML editor. This control gives users a rich text editing experience specific for outputting HTML. The user interaction for this control will be familiar to your users – they can use tool bar buttons to apply formatting to selected text, and navigate the text using the Home, End, Ctrl, Shift, arrow key and mouse combinations. The available formatting options include bold, italic, underline, foreground color, background color, font family, font size, hyperlinks, ordered/unordered lists, left, right, center and justified alignments. Based on customer feature requests, we’ve added built-in spell checking support to this control which your users will love.

Enabling the Spell Checker

To enable the built-in spell checker, simply set the IsSpellCheckingEnabled property of our RichTextEditor to true.

<ms:RichTextEditor x:Name="TextEditor" IsSpellCheckingEnabled="True" />

As the user is editing the text, the well known red squiggly lines appear under any words not found in the dictionary. By default, the United States dictionary will be used for checking the spelling. A UK dictionary is also available which you can use by setting the SpellingDictionary property to UnitedKingdom.

Spell Checker Enabled

Right clicking on a misspelt word will display a context menu of suggestions. The suggestion list is ordered with the most likely correct word at the top. Selecting one of the suggestions will replace the misspelt word.

Context Menu

Spelling Dialog

The HTML editor also comes with a built-in spelling dialog which will be familiar to Microsoft Office users. The dialog lets the user navigate through each misspelt word in the document and either ignore the word, or change it to one of the suggestions. There are also commands for applying changes to all the same misspelt words in the document. The dialog can be opened by pressing the spell check button in the HTML toolbar. By default the button is not displayed, so to display it, simply set the IsSpellCheckButtonVisible property on the StandardRichTextEditorToolBar to true.

<ms:StandardRichTextEditorToolBar Editor="{Binding ElementName=TextEditor}" IsSpellCheckButtonVisible="True" />

Spelling Dialog

More New Features

Here are some other new features in the latest version of the HTML editor that you may be interested in:

  • Tab key support
    By default, the Tab key is used to navigate focus to the next control in the Silverlight application. By setting the RichTextEditor.CanHandleTabKey property to true, the Tab key will be used for indenting paragraphs. Pressing the Tab key at the very start of a paragraph will indent the first line. In HTML, this is the text-indent style. Pressing the Tab key anywhere else will cause the whole paragraph to be indented. This affects the padding-left style in the HTML output. Pressing Shift+Tab will reverse the effects. The TabSize property can be used to specify the pixel size of the tab.
  • Hex Color Encoding
    By default, the HTML output that the control produces will encode foreground and background colors using the RGB format. If you set the RichTextEditor.ColorEncoding property to Hex, then the HTML output will use hex encoding for the colors. When importing HTML, the editor will happily accept both color formats.
  • Copy Rich Formatting
    The editor now also preserves rich text formatting when copying and pasting within the editor.

To take advantage of these new features in your applications, make sure to download the latest nightly build. You can download the free trial version from here, or go to your account page if you’re already a customer. If you have any questions or feature requests, let us know in the forum.

WPF Elements: New Color Picker Features

One of the neat controls in our WPF Elements control suite is the color picker. Color pickers are a great addition to your WPF tool box as they are useful in all sorts of different applications. Rather than providing a single color picker control with options to display different parts, we provide several color picking components that you can piece together to create whatever color picking UI that you need. Most of these components can even be used standalone as simple color picker controls. Using data templates, you can also include additional functionality. The main components are:

The ColorPicker which displays a palette of colors that the user can select.

Color Picker

The HsvColorPicker which is modelled from the Expression Blend color picker.

HSV Color Picker

The ChannelColor picker which provides sliders and numeric up downs for editing individual color channels such as R,G,B and Alpha.

Channel Color Picker

And the DropDownColorPicker which always displays the selected color but hides away the actual color picker UI until the user wants to edit it. Below is an image of the default set up of the DropDownColorPicker. Notice that it includes all the other components I’ve mentioned above which creates a UI for the user to select a color in almost any way they like.

Drop Down Color Picker

By changing the header template and drop down template, you can create a different color picker UI that suites the requirements of your application.

The Color Text Box

Color Text Box

Based on customer feedback we have added a couple of new features to this color picker suite. The first feature is a whole new component: the ColorTextBox. This control lets the user view and edit the selected color as a hexadecimal value. This is fantastic for applications designed for users who are used to editing colors as hexadecimal values such as web developers or graphic designers. The parser supports common hexadecimal color formats such as hash or no hash, 8 digits for including the alpha channel, 6 digits for opaque colors and 3 digits for shorthand formatting (e.g. #123 would be treated as #112233).

In terms of displaying the selected color, there are a few options for specifying how the selected color gets encoded. If AlwaysShowAlphaHexEncoding is true, the encoded color will always be displayed with 8 digits. If this is false, the alpha encoding will not be displayed if the color is fully opaque. IsHashSymbolDisplayed lets you specify if the hash prefix is included in the displayed string. by setting IsMinimizeHexEncodingEnabled to true, the hex encoding will be shortened to 3 digits where possible.

A couple of other useful properties are: SelectAllOnEntry and UpdateSelectedColorWhileEditing. If SelectAllOnEntry is true, all the text will be selected when the control gains focus. This can be convenient for quickly getting in and editing or copying the entire color value. UpdateSelectedColorWhileEditing is true by default which means the selected color value changes in real time as the user is editing the hex value. By setting this to false, the selected color will only be updated when the control loses focus or the enter key is pressed.

HSV Color Sliders

The other new feature we have added are additional sliders to the ChannelColorPicker control for editing the HSV values of a color. By default, the ChannelColorPicker will still only display the RGB and Alpha sliders. You can use these 3 new properties to change which sliders get displayed: IsRgbVisible, IsHsvVisible and IsAlphaVisible.

HSV Color Sliders

Customization

As I mentioned before, you can use a data template to piece together the various color picker components to create your own color picker UI. Here I’ll give you an example of how to make a custom DropDownColorPicker UI. Lets start with the header template. This is to customize the appearance of the selected color display that is not hidden in the drop down. The default template simply displays the selected color in a TextBlock with an appropriate english name. Lets use the new ColorTextBox control giving the users an option to edit the color as a hexadecimal value without needing to open the drop down. Here is the code for this template which includes a border element to visualize the selected color alongside the ColorTextBox.

<ms:ColorToBrushConverter x:Key="ColorToBrush" />
 
<DataTemplate x:Key="HeaderTemplate">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Border Background="{Binding SelectedColor, Converter={StaticResource ColorToBrush}}"
                BorderBrush="Black" BorderThickness="1" Margin="2,0,6,0" SnapsToDevicePixels="True"
                Width="{Binding ActualHeight, RelativeSource={RelativeSource Self}}" />
        <ms:ColorTextBox Grid.Column="1" BorderThickness="0" SelectedColor="{Binding SelectedColor, Mode=TwoWay}" VerticalAlignment="Center"
                         IsHashSymbolDisplayed="True" IsMinimizeHexEncodingEnabled="True" SelectAllOnEntry="True" UpdateSelectedColorWhileEditing="False" />
    </Grid>
</DataTemplate>

Next is the drop down template. Here I’ve taken the default template and modified it to include the new HSV color sliders and another ColorTextBox. Most of the controls are in the MoreColorsTemplate which defines what to display in the “More Colors” secondary popup. The drop down template includes a color palette and a MoreColorsButton. You can use this code as a starting point for making your own UI.

<DataTemplate x:Key="MoreColorsTemplate">
    <DockPanel>
        <Border Background="{StaticResource MenuBackground}" DockPanel.Dock="Bottom">
            <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
                <Button Content="OK" Width="80" Margin="5" Command="{x:Static ms:MoreColorsButtonCommands.AcceptColor}" />
                <Button Content="Cancel" Width="80" Margin="5" Command="{x:Static ms:MoreColorsButtonCommands.CancelColor}" />
            </StackPanel>
        </Border>
        <Border Height="1" Background="{StaticResource Border}" DockPanel.Dock="Bottom" />
        <Grid DockPanel.Dock="Left" Margin="3,3,0,3">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>
            <ms:HsvColorPicker x:Name="HSVPicker" Width="180" Height="180"
                               SelectedColor="{Binding NewColor, Mode=TwoWay, RelativeSource={RelativeSource AncestorType={x:Type ms:MoreColorsButton}}}" />
            <ms:ColorTextBox Grid.Row="1" Margin="0,3,0,0" SelectedColor="{Binding NewColor, Mode=TwoWay, RelativeSource={RelativeSource AncestorType={x:Type ms:MoreColorsButton}}}"
                             IsHashSymbolDisplayed="True" />
        </Grid>
        <Border BorderBrush="Black" Padding="1" Background="White" CornerRadius="2" Margin="5,2,5,3" Height="22"
                DockPanel.Dock="Bottom" BorderThickness="1">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <Border Background="{Binding CurrentColor, Converter={StaticResource ColorToBrush}, RelativeSource={RelativeSource AncestorType={x:Type ms:MoreColorsButton}}}" />
                <Border Background="{Binding NewColor, Converter={StaticResource ColorToBrush}, RelativeSource={RelativeSource AncestorType={x:Type ms:MoreColorsButton}}}" Grid.Column="1" />
        </Grid>
        </Border>
            <ms:ChannelColorPicker Width="180" BorderThickness="0" Height="180" H="{Binding H, Mode=TwoWay, ElementName=HSVPicker}" IsHsvVisible="True"
                                   SelectedColor="{Binding NewColor, Mode=TwoWay, RelativeSource={RelativeSource AncestorType={x:Type ms:MoreColorsButton}}}" />
    </DockPanel>
</DataTemplate>
<DataTemplate x:Key="DropDownTemplate">
    <Border BorderBrush="{Binding BorderBrush}" BorderThickness="1">
        <StackPanel>
            <ms:ColorPicker Palette="{Binding Palette}" SelectedColor="{Binding SelectedColor}" BorderThickness="0" />
            <ms:MoreColorsButton CurrentColor="{Binding SelectedColor}" ContentTemplate="{StaticResource MoreColorsTemplate}" BorderThickness="0,1,0,0" />
        </StackPanel>
    </Border>
</DataTemplate>

And to finish it off, you can apply these templates to the DropDownColorPicker in your application:

<ms:DropDownColorPicker HeaderTemplate="{StaticResource HeaderTemplate}" DropDownTemplate="{StaticResource DropDownTemplate}" />

Custom Color Picker

These new features are available right now in the current nightly build. If you are currently playing around with the trial version, or want to give it a try, you can download the free trial from here. If you are already a customer, you can download the latest nightly build from your account page.

If you have any questions about any of our WPF controls, come meet us in the forum.

Web Workbench Sass Performance Update

If you’re a Web Workbench user and work with Sass you’ll be pleased with the recent update through the Visual Studio Gallery. We’ve made the decision to migrate away from IronRuby for the Ruby runtime used for running the Sass compiler and this has added a significant speed boost for those of you working with Sass files.

There is one minor breaking change in this release. Where previously you could pass in arguments to the Sass compiler in the file with this hash syntax:

//* scss-compile-options: :style => :compressed

You now need to use this format:

//* scss-compile-options: --style compressed

This is due to changes in the way that we need to run the Sass compiler. Fortunately it’s a quick change to make if you’re using these arguments in your Sass files and you’ll get the benefit of significantly faster compilation times!

Not using the Web Workbench yet? Grab the free edition from the Visual Studio Gallery!

WPF Elements 5.1 Released!

We’re really pleased to be releasing WPF Elements 5.1 today with new controls, high powered performance improvements and new features. If you’re a WPF developer we think you’ll love the full WPF Elements Suite. Here’s a high level run through of key improvements in 5.1.

Data Grid Enhancements

WPF Datagrid control

The WPF Data Grid control in WPF Elements 5.1 is a much improved beast when compared with the 5.0 release. We had a lot of feedback from developers and we have been listening. Improvements in the 5.1 Data grid include:

  • Grouping support with support for multi-level grouping and the ability to expand and collapse groups
  • Exporting support (CSV exporting built in)
  • Custom column sorting is supported
  • Additional cell editing modes (e.g. double click to edit, etc)
  • Row selection mode when clicking on a row header
  • Support for hierarchical data in the same way as a TreeView control
  • Allow users to add new rows which adds items to the underlying collection
  • Binding to DataTable and IBindingList data sources is now supported
  • RowHeaderTemplate support added for custom row headers
  • ColumnHeaderTemplate support for custom column headers
  • DataGrid.DisplayMemberBinding support for more complex binding scenarios without needing custom cell templates
  • Background and foreground colors can be set for rows, columns or even individual cells
  • Programmatically control scroll position (e.g. scroll to selected row, or end, etc)
  • Auto sizing and * (star) sizing support for column widths

Of course these are just the key new features on top of our already super fast virtualized data grid engine.

Charting Enhancements

Along with the new charts detailed below, we made many improvements to the existing charts. The key focus for this release with regards to charts: Speed. LOTS OF SPEED. We already had pretty good charting performance (one customer compared against 10 different WPF Charting options and found we provided the best speed + features offering. They’ll be impressed with this release then!).

WPF Charting Speed - Supremely fast!

WPF Elements 5.1 charts can render millions of data points in a matter of milliseconds!

We’ll be posted more about these improvements in the coming days. Improvements in performance are across all chart types – you don’t need to choose between features and performance with WPF Elements!

Other charting enhancements include:

  • BarSeries, StackedBarSeries and ScatterSeries now support millions of data points.
  • Setting ChartAxis.IsSliderVisible to true will display the built-in axis slider. This is an alternate way for the user to zoom and pan the chart.
  • You can now specify the starting value of the logarithmic axis scale.
  • MarkedStripeGrid supports both vertical and horizontal orientations.
  • You can now specify the logical position of the baseline in bar charts.
  • You can now specify the number of minor tick marks rendered between major tick marks.
  • Setting the DataSeries.IsShownInLegend property can hide the legend item for that series.

New Chart: Boxplot

WPF Elements now includes the WPF Boxplot. It’s built on the same high performance core charting engine as all the other charts in WPF Elements.

WPF Box Plot Chart

New Chart: Candle Stick

WPF Elements users also get the WPF Candle Stick chart. A handy chart for financial data and, like all other charts, super fast as well!

WPF Candle Stick Chart

New Chart: Stock Chart

The third new chart type added is the WPF Stock Chart. Guess what? It’s also super fast and built on the same engine as the other charts!

WPF Stock Chart

It’s not all charts and grids!

While the Data Grid and Charts got a good number of enhancements and performance boosts, we love all our controls the same. A few of the other changes found across the suite are:

  • You can now template the various scheduler dialog boxes. This is useful for providing custom styles or for localizing the labels.
  • Added a new IntegerUpDown control.
  • Added PercentageTextBox control.
  • Some more free WPF controls included in our free suite (we’ll post more about this later)

Dig in, build awesome apps

Last but not least is that we’ve added more samples to our sample explorer that’s included in all releases of WPF Elements. You can explore new functionality, examine the code used to make that sample and adjust the look and feel from within the sample explorer. Once you’ve installed WPF Elements you can find the Sample Explorer in the Start Menu. If you need a hand getting started, we would love to help.

Get the 60 day free trial of WPF Elements 5.1
Existing customers can download 5.1 from their account

Archives

Join our mailer

You should join our newsletter! Sent monthly:

Back to Top