European Silverlight 4 & Silverlight 5 Hosting BLOG

BLOG about Silverlight 5 Hosting and Its Techologies - Dedicated to European Windows Hosting Customer

European Silverlight 5 Hosting - Amsterdam :: Animation in Silverlight 5 Using VisualStateManager.LoadTransition

clock July 5, 2013 06:24 by author Scott

I was quite happy to see the all those sleek new additions to silverlight 5. I will be addressing all of them one by one. For the timebeing i will show how to give that nice and smooth initial animation when a control is loading. Before silverlight 5, this was pretty time consuming as you required to write all those custom animation codes and have their triggers in place. Now all you need to do is the following :

<Grid>
<VisualStateManager.LoadTransition>
<LoadTransition StartXOffset="300" GeneratedDuration="0:0:1.0" StartOpacity="0.2">
<LoadTransition.GeneratedEasingFunction>
<CircleEase/>
</LoadTransition.GeneratedEasingFunction>
</LoadTransition>
</VisualStateManager.LoadTransition>
</Grid>

As we can see above, its a very simple usage. All we need to do is add the VisualStateManager.LoadTransition to our Grid. The parameters are quite self explanatory :

  • StartXOffset : The intial x co-ordinate from which to start the transition
  • GeneratedDuration : The amount of time it would animate
  • StartOpacity : The initial Opacity. Here it start with an initial opacity of 20%
  • Also notice that we have added an easing function of type CircleEase. (More details on it at : http://msdn.microsoft.com/en-us/library/ee308751.aspx)


European Silverlight Hosting - Amsterdam :: How to Enable Dynamic Compression in IIS 7/7.5

clock February 18, 2013 07:47 by author Scott

In this tutorial I will show you how to enable dynamic compression in IIS 7. For other post of dynamic compression, please just see our last post.

You’ll see this error message when you haven’t setup dynamic compression on your IIS:

“The dynamic content compression module is not installed.”

Ok, let’s start the tutorial:

1. Open server manager

2. Roles --> IIS

3. Role Services (scroll down) --> Add Role Services

4. Add desired role (Web Server --> Performance > Dynamic Content Compression)

5. Wait till finish.

To enable this feature, here are the steps:

1. Open server manager

2. Roles --> Web Server (IIS) --> Internet Information Services (IIS) Manager

3. Then, go to your site --> your website

4. IISà compression

And dynamic compression has been enable on your server. Hope this tutorial is interesting.

 



European Silverlight 5 Hosting - Amsterdam :: Markup Extensions in Silverlight 5

clock September 28, 2012 09:03 by author Scott

Another cool feature available in Silverlight 5 is markup extensions. The idea behind the feature is ability to allow developers to supply values to XAML parser at the time it parses visual tree. In other words, once parser finds a markup extension in XAML, it will create an instance of it, set any properties that the extension might have, then call ProvideValue method that will return a value of the type that the property that markup extension supports expects. For example, I am writing a markup extension to supply an ICommand to the button, my XAML would looks like the following:

      <Button Content="Save" HorizontalAlignment="Left"  
             Grid.Row="4" Grid.Column="0"
             Command="{ext:CommandMarkupExtension
                 ViewModel={Binding ElementName=LayoutRoot, Path=DataContext},
                 ExecuteMethodName=Run,
                 CanExecuteMethodName=CanRun}"/>


So, in this example for markup extension I am writing a command extension. As you can see in the XAML above, my extension takes three parameters: ViewModel to invoke, execute and can execute method names. This way I can de-clutter my view model by removing all the command instantiation code, and just write the two methods I need. The code in this extension is very easy – just a handful of dependency properties and interface implementation for IMarkupExtension:

using System;

using System.Windows;

using System.Windows.Input;

using System.Xaml;


namespace SL5Features.Extensions

{

  public class CommandMarkupExtension : FrameworkElement, IMarkupExtension<ICommand>
  {

    public Object ViewModel
    {
      get { return (Object)GetValue(ViewModelProperty); }
      set { SetValue(ViewModelProperty, value); }
    }

    public static readonly DependencyProperty ViewModelProperty =
        DependencyProperty.Register(
        "ViewModel", typeof(Object),
        typeof(CommandMarkupExtension),
        new PropertyMetadata(null));

    public string ExecuteMethodName
    {
      get { return (string)GetValue(ExecuteMethodNameProperty); }
      set { SetValue(ExecuteMethodNameProperty, value); }
    }
    public static readonly DependencyProperty ExecuteMethodNameProperty =
        DependencyProperty.Register(
        "ExecuteMethodName",
        typeof(string),
        typeof(CommandMarkupExtension),
        new PropertyMetadata(null));


    public string CanExecuteMethodName
    {
      get { return (string)GetValue(CanExecuteMethodNameProperty); }
      set { SetValue(CanExecuteMethodNameProperty, value); }
    }

    public static readonly DependencyProperty CanExecuteMethodNameProperty =
        DependencyProperty.Register(
        "CanExecuteMethodName",
        typeof(string),
        typeof(CommandMarkupExtension),
        new PropertyMetadata(null));

    public ICommand ProvideValue(IServiceProvider serviceProvider)
    {
      ReflectionCommand command =
        new ReflectionCommand(ViewModel, ExecuteMethodName, CanExecuteMethodName);
      return command;
    }
  }
}

To support the extension I need to write a command object that would actually implement ICommand. This class is pretty trivial, so I am not commenting it much:


using System;

using System.Reflection;

using System.Windows;

using System.Windows.Input;  


namespace SL5Features.Extensions

{

  public class ReflectionCommand : ICommand
  {

    private MethodInfo canExecuteMethod = null;
    private MethodInfo executeMethod = null;
    private object viewModel = null;

    private ReflectionCommand() {


    public ReflectionCommand(
      object viewModel,
      string executeMethodName,
      string canExecuteMethodName)
    {
      this.viewModel = viewModel;
      Type type = viewModel.GetType();
      if (!string.IsNullOrEmpty(canExecuteMethodName))
      {
        this.canExecuteMethod = type.GetMethod(canExecuteMethodName);
      }
      this.executeMethod = type.GetMethod(executeMethodName);
    }

    public void Execute(object parameter)
    {
      executeMethod.Invoke(viewModel, new[] { parameter });
    }

    public bool CanExecute(object parameter)
    {
      if (viewModel != null && canExecuteMethod != null)
      {
        return (bool)canExecuteMethod.Invoke(viewModel, new[] { parameter });
      }
      else
      {
        return true;
      }
    }



    public event EventHandler CanExecuteChanged;

    public void RaiseCanExecuteChanged()
    {
      if (CanExecuteChanged != null)
      {
        CanExecuteChanged(this, EventArgs.Empty);
      }
    }

  }
}

So, far it is pretty easy. Now, all I have to do is add Run and CanRun method on my view model that my command will invoke:

using SL5Features.Models;
using System.Windows;

namespace SL5Features.ViewModels

{
  public class PersonViewModel : ViewModelBase<Person
  {
    public PersonViewModel()
    {
      Model = new Person() { FirstName = "Sergey", LastName = "Barskiy" };
    }

    public void Run(object parameter)
    {
      MessageBox.Show("Run")
    }
    public bool CanRun(object parameter
    {
      return true;
    }
  }
}


Hopefully, I demonstrated the power of markup extension for you. The goal of using them to me is reduction of the amount of code elsewhere in the system, since you will obviously have to write more XAML. Of course, I am sure Blend 5 will support mark up extensions, so potentially you can just drag my extension on top of the button and setup a few properties in properties window. You will also see a number of demos where an extension is used to support localization, which seems pretty intuitive use of the feature. Bottom line is: I love getting new features that make my job easier by allowing me to write less code and re-use more of the code written.

 



European Silverlight 5 Hosting - Amsterdam :: Breakpoints on Xaml in Silverlight 5

clock July 13, 2012 09:45 by author Scott

Silverlight 5 Beta brings the enormously useful ability to set a break point in your Xaml where you have a data binding. This can greatly simplify debugging and fixing binding issues.



To see this, create a new Silverlight 5 project and set up the Xaml to have 5 rows and 2 columns. Place the title in the first row (spanning both columns) and prompts in the next 4 rows. The prompts are


- FullName

- Address
- Phone
- Email

Add four TextBlocks in the second column to display the values that will correspond to these prompts. The Xaml for the four prompts looks like this:


<TextBlock
    Grid.Column="1"
    Grid.Row="1"
    Margin="5"
    HorizontalAlignment="Left"
    VerticalAlignment="Center"
    Text="{Binding FullName}" />
<TextBlock
    Grid.Column="1"
    Grid.Row="2"
    Margin="5"
    HorizontalAlignment="Left"
    VerticalAlignment="Center"
    Text="{Binding Address}" />
<TextBlock
    Grid.Column="1"
    Grid.Row="3"
    Margin="5"
    HorizontalAlignment="Left"
    VerticalAlignment="Center"
    Text="{Binding PhoneNumber}" />
<TextBlock
    Grid.Column="1"
    Grid.Row="4"
    Margin="5"
    HorizontalAlignment="Left"
    VerticalAlignment="Center"
    Text="{Binding Email}" />

To make this work, of course, we need a class and an instance to bind to. Begin by creating a new class, Person,


public class Person

{

    public string FullName { get; set; }
    public string Address { get; set; }
    public string Phone { get; set; }
    public string Email { get; set; }
}

In MainPage.xaml.cs create an instance of Person, and set that instance to be the data context for the bindings,


public MainPage()
{
    InitializeComponent();
    var per = new Person()
    {
        FullName = "Jesse Liberty",
        Address = "100 Main Street, Boston, MA",
        Email = "[email protected]",
        Phone = "617-555-1212"
    };
    this.DataContext = per;
}

When you run this you’ll find that three of the four bindings work well, but the phone number is not displayed. Set a break point in the Xaml folder on the binding for the PhoneNumber and run the application. When you hit the break point examine the locals window as shown in the illustration to the below.



Note that there is an error message. By clicking on the message you can open a text reader for the entire error message, as shown in the next figure to the below.




The error message indicates that there is no property PhoneNumber in the type Person, and sure enough, a quick check of the code shows that the property is just
Phone.

Change the binding from PhoneNumber to Phone and the program works as expected.



European Silverlight 5 Hosting - Amsterdam :: How to Design RichTextBox in Silverlight 5

clock June 29, 2012 08:54 by author Scott

In this article, I am going to explain how to design a RichTextBox in Silverlight. This example also demonstrates the RichTextBox control as well. It is easy to formatt a Silverlight RichTextBox at design time through XAML. In this example I have used an image to illustrate the example clearly.

<UserControl x:Class="SilverlightApplication3.MainPage"
                  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"
                  d:DesignHeight="300" d:DesignWidth="400" DataContext="{Binding}">

              <Grid x:Name="LayoutRoot" Background="White" Height="450" Width="550">
                      <RichTextBox HorizontalAlignment="Left" Margin="10,12,0,0" Name="contentBox" VerticalAlignment="Top" Height="330" Width="390" IsReadOnly="True" Background="#FFFFFF69">
                    <Paragraph FontFamily="Arial" FontSize="12" TextAlignment="Justify">
                   This photograph shows a
                <Run Text=" blue hills " FontStyle="Italic" FontWeight="ExtraBold" /> belongs to the
                <Run Text=" high " Foreground="blue" FontWeight="ExtraBold"/> graphic photography. High graphic photography requires a     great deal of precision.
                <LineBreak/>
                <InlineUIContainer>
                    <Image Height="143" HorizontalAlignment="Left" Margin="144,82,0,0" Name="images" Stretch="Uniform" VerticalAlignment="Top" Width="196" Source="/SilverlightApplication3;component/Images/Blue%20hills.jpg" />
                </InlineUIContainer>
                <LineBreak/>
                <LineBreak/> |
          </Paragraph>
        </RichTextBox>
    </Grid>
</UserControl>

Now I am going to explain the code so that it can be easily understood. It creates a RichTextBox, with some text and an image. To place and format the text, I first use the Paragraph element, then the Run element. Note that the Paragraph element also has a Foreground property but which I have not used here. In this I use the Run element which is useful to format text. The RichTextBox control also allows you to add elements of type Bold, Underline etc.The Run element derives from the Inline element, an Inline cannot be used directly within a RichTextBox control, however, you can use the Run element.


The LineBreak element is used to introduce line breaks.

The Image is placed inside the InlineUIContainer.

InlineUIContainer: A mandatory child element that is used to place an Image in the RichTextBox control.

You can have as many Paragraph and Run elements as you want, in a RichTextBox control. Using a combination of Paragraph and Run elements, you can format the text in various ways.

The output of the above application is shown below:



European Silverlight 5 Hosting - Amsterdam :: Platform Invocation Services in Silverlight 5

clock June 13, 2012 08:26 by author Scott

One of the new features included with the Silverlight 5 RC is the ability to interact with Platform Invocation Services, or PInvoke for short. This functionality allows managed code, like your Silverlight application, to make calls to unmanaged code like the C++ code that exists in DLLs on your system. PInvoke can be quite complex and covers a lot of different scenarios, so I've focused on a simple scenario to help you get started. You can learn more about PInvoke by reading this MSDN tutorial.

In this post, I will show you how to build a Silverlight Out-of-Browser (OOB) application that uses the native DLLs on your machine to play "beeps." With modern versions of Windows 7, the beeps have evolved into complex sounds that you can assign to various functions. Create a new Silverlight application called "PInvoke," set it to run out of browser and be sure to check the box that indicates it requires elevated trust.


Take a look at the MessageBeep function. It is documented
here. The first thing you'll notice is that the type of beep or sound to play is not very friendly as it is passed in as an unsigned integer. Based on the documentation, you can create the following enumeration to simplify things and expose a few key types:

1 public enum BeepTypes : uint
2 { 
3     Ok = 0x00000000, 
4     Error = 0x00000010, 
5     Warning = 0x00000030, 
6     Information = 0x00000040 
7 }

To make it easy to take a string and cast it to the enumeration value, add this extension method as well:


01 public static class BeepTypeExtensions 
02 { 
03     public static BeepTypes AsBeepTypeEnum(this string beepType) 
04     { 
05         BeepTypes beepTypeEnum; 
06         return Enum.TryParse(beepType, true, out beepTypeEnum) 
07                     ? beepTypeEnum 
08                     : BeepTypes.Error; 
09     } 
10 }


It is always good practice to encapsulate your calls to unmanaged code in a managed class. This limits the exposure and dependency on PInvoke. It also allows you to write more portable code because you can implement the calls in managed code or simply stub out empty methods for targets that don't support the PInvoke implementation. Here is a simple contract to play a sound:


1 public interface ISoundPlayer 
2 { 
3     void PlaySound(BeepTypes type); 
4 }


Now for the implementation. Create a class called
SoundPlayer. The documentation gives you the message signature and the DLL that the method is located in. Bridging to the method in this example is very easy. First, include a using statement for System.Runtime.InteropServices. This is where the PInvoke bridge lives. Next, simply define the message signature as a static extern and import the DLL:

1 [DllImport("User32.dll")] 
2 private static extern Boolean MessageBeep(UInt32 beepType);

Implement the contract and call the method you just imported using PInvoke:


1 public void PlaySound(BeepTypes type) 
2 { 
3     if (!MessageBeep((UInt32) type)) 
4     { 
5         throw new Exception("Beep failed!"); 
6     } 
7 }

That's all there is to it! Now wire up some Xaml in the main page to host four buttons:

01 <Grid x:Name="LayoutRoot" Background="White"> 
02     <Grid.RowDefinitions> 
03         <RowDefinition Height="1*"/> 
04         <RowDefinition Height="1*"/> 
05     </Grid.RowDefinitions> 
06     <Grid.ColumnDefinitions> 
07         <ColumnDefinition Width="1*"/> 
08         <ColumnDefinition Width="1*"/> 
09     </Grid.ColumnDefinitions> 
10     <Button x:Name="Ok" Content="OK" Grid.Row="0" Grid.Column="0"  Click="Button_Click"/> 
11     <Button x:Name="Error" Content="Error" Grid.Row="0" Grid.Column="1"  Click="Button_Click"/> 
12     <Button x:Name="Warning" Content="Warning" Grid.Row="1" Grid.Column="0"  Click="Button_Click"/> 
13     <Button x:Name="Information" Content="Information" Grid.Row="1" Grid.Column="1"  Click="Button_Click"/> 
14 </Grid>

Make sure that the name of the button matches the name of the enum. In the code-behind for the main page, create an instance of the sound player:

1 private readonly ISoundPlayer _soundPlayer = new SoundPlayer();

Now you can implement the button click event. Simply cast the name of the button to the enumeration and call the method on your managed class:


1 private void Button_Click(object sender, RoutedEventArgs e) 
2 { 
3     var button = sender as Button; 
4     if (button == null) 
5     { 
6         return; 
7     } 
8     _soundPlayer.PlaySound(button.Name.AsBeepTypeEnum()); 
9 }

That's it! Run the application in OOB mode and you will be able to press the buttons and hear your default Windows sounds play. If you change your theme or override the sounds, the application will play the correct sounds because it is bridging to the unmanaged code and asking the operating system to play the sound rather than trying to play it from a resource embedded within the Silverlight application.


Hopefully this light example will help you get started. PInvoke has a number of uses from interfacing directly with USB ports to enumerating drives and devices on the host system. It certainly opens the door to a new realm of possibilities with Silverlight.

 



European Silverlight 5 Hosting - Amsterdam :: Using the ViewBox Control in Silverlight 5

clock May 14, 2012 08:40 by author Scott

This article will explore how to use the ViewBox control in Silverlight 5.

The ViewBox control allows you to place a child control such as Image within it in such a way that it will be scaled appropriately to fit the available without any distortion. It is typically used in 2D graphics.


We will begin with creating a new Silverlight 5 project.


Modify the existing XAML code of MainPage.xaml so that a Grid of 1 column and three rows is created. The code for the same is shown below:


<UserControl x:Class="SilverlightDemo.MainPage"
     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:sdk=http://schemas.microsoft.com/winfx/2006/xaml/presentation/ sdk HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
     <Grid x:Name="LayoutRoot" Background="White" Height="300" Width="300">
         <Grid.ColumnDefinitions>
             <ColumnDefinition Width="200" />
         </Grid.ColumnDefinitions>
         <Grid.RowDefinitions>
             <RowDefinition Height="Auto" />
             <RowDefinition Height="Auto" />
             <RowDefinition Height="Auto" />
         </Grid.RowDefinitions>
     </Grid>
 </UserControl>


Drag and drop the Viewbox control from the Toolbox into the XAML code between the <Grid></Grid> tags. Specify its row and column in the grid to be 0. The resulting code is seen below.


<UserControl x:Class="SilverlightDemo.MainPage"
     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:sdk=http://schemas.microsoft.com/winfx/2006/xaml/presentation/ sdk HorizontalAlignment="Stretch" VerticalAlignment="Stretch">        <Grid.ColumnDefinitions>
             <ColumnDefinition Width="200" />
         </Grid.ColumnDefinitions>
         <Grid.RowDefinitions>
             <RowDefinition Height="Auto" />
             <RowDefinition Height="Auto" />
             <RowDefinition Height="Auto" />
         </Grid.RowDefinitions>
          <controls:Viewbox Grid.Row="0" Grid.Column="0" Height="120" Width="120">
   </controls:Viewbox> 
    </Grid>
 </UserControl>

Right click on the project name in the Solution Explorer pane and select Add Existing Item option. Choose the image "Winter.jg" from the My Documents\My Pictures\Sample Pictures folder.


Drag and drop an Image control in between the <controls:ViewBox> and </controls:ViewBox> tag and modify its code as shown below, to specify its source and size.


    <Grid x:Name="LayoutRoot" Background="White" Height="300" Width="300">
         <Grid.ColumnDefinitions>
             <ColumnDefinition Width="200" />
         </Grid.ColumnDefinitions>
         <Grid.RowDefinitions>
             <RowDefinition Height="Auto" />
             <RowDefinition Height="Auto" />
             <RowDefinition Height="Auto" />
         </Grid.RowDefinitions>
          <controls:Viewbox Grid.Row="0" Grid.Column="0" Height="120" Width="120">
             <Image Source="Winter.jpg" Height="40" Width="40"></Image>
         </controls:Viewbox>
     </Grid>

Drag and drop another ViewBox and then an Image control in between the second <controls:ViewBox> and </controls:ViewBox> tag.

Modify the XAML as shown below:


    <Grid x:Name="LayoutRoot" Background="White" Height="300" Width="300">
         <Grid.ColumnDefinitions>
             <ColumnDefinition Width="200" />
         </Grid.ColumnDefinitions>
         <Grid.RowDefinitions>
             <RowDefinition Height="Auto" />
             <RowDefinition Height="Auto" />
             <RowDefinition Height="Auto" />
         </Grid.RowDefinitions>
          <controls:Viewbox Grid.Row="0" Grid.Column="0" Height="120" Width="120">
             <Image Source="Winter.jpg" Height="40" Width="40"></Image>
         </controls:Viewbox>
 <controls:Viewbox Grid.Row="1" Grid.Column="0" Height="70" Width="90">
     <Image Source="Winter.jpg" Height="40" Width="40"></Image></controls:Viewbox>
     </Grid>


Save the solution, build and execute it. When you see the output, you will observe that the two images show no distortion whatsoever though their height and width are not the same. This has happened because of the ViewBox.




Conclusion
: Thus, you learnt how to add and use a ViewBox control in a Silverlight application



European Silverlight 5 Hosting - Amsterdam :: Client-side Collections Silverlight 5

clock April 24, 2012 06:33 by author Scott

With the release of Silverlight 5 just around the corner, I thought I would start a series on the new PivotViewer and how to get up and running with it. We will start the series off by exploring how to create a client side collection.

One of the most anticipated features of the new PivotViewer is the ability to create client-side collections. PivotViewer accomplishes this by utilizing the traditional ItemsSource property for data and a form of XAML data templates to define the trading card. It is interesting to note that the fundamental core of PivotViewer is still using the DeepZoom technology. If you are thinking that DeepZoom only handles images and not XAML, you would be correct. Under the hood, PivotViewer is rendering the data templates to images and then adding those images to DeepZoom. Remembering that little tidbit will help later down the road.


The Basics


First things first, let’s get a PivotViewer control into our application. One of the great changes in the PivotViewer is that instead of 4 libraries we are down to one. So to include the PivotViewer in your application, you simple need to add a reference to System.Windows.Controls.Pivot.


Now we can add a PivotViewer to our application like this:


<Grid x:Name="LayoutRoot" Background="White">

    <pivot:PivotViewer x:Name="pViewer"/>
</Grid>


Doesn’t get much simpler than that, now does it?


Getting your Data


In order to focus in our demo, we are going to generate some dummy data on the client. Of course, you are most likely going to be pulling in more meaningful data (let’s hope anyway) and you can still do that in the traditional ways.


public class DemoItem : INotifyPropertyChanged

{

    public string ShortName { get; set; }

    private string _color;
    public string Color
    {
        get { return _color; }
        set
        {
            _color = value;
            NotifyProperty("Color");
        }
    }

    private int _value;
    public int Value

    {
        get { return _value; }
        set
        {
            _value = value;
            NotifyProperty("Value");
        }
    }

    private string _data1;
    public string Data1
    {
        get { return _data1; }
        set
        {
            _data1 = value;
            NotifyProperty("Data1");
        }
    }

    private DateTime _stamp;
    public DateTime Stamp
    {
        get { return _stamp; }
        set
        {
            _stamp = value;
            NotifyProperty("Stamp");
        }
    }

    public static ObservableCollection<DemoItem> BuildData()
    {
        var data = new ObservableCollection<DemoItem>();

        for (int i = 0; i < 100; i++)
        {
            var itm = new DemoItem()
             { ShortName = i.ToString("000") };

            var mod = i % 3;

            switch (mod)
            {
                case 0:
                    itm.Color = "Blue";
                    break;
                case 1:
                    itm.Color = "Red";
                    break;
                case 2:
                    itm.Color = "Green";
                    break;
            }

            itm.Data1 = i % 2 == 0 ? "Even" : "Odd";
            itm.Stamp = DateTime.Now.AddDays(-1*i);
            data.Add(itm);
        }

        return data;
    }

    #region INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyProperty(string propName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this,
              new PropertyChangedEventArgs(propName));
    }

    #endregion

}

As you can see there isn’t a whole lot going on here. The BuildData() method knocks out some data that will let us see PivotViewer in action. I used a string for the color property so it would map to a PivotViewer property cleanly.


Now that we can generate our data, how do we get it into PivotViewer? It’s as simple as using the ItemsSource property (yep just like a normal Silverlight control).

pViewer.ItemsSource = DemoItem.BuildData();

Setting up your PivotProperties

In the original PivotViewer properties were defined as facets. In the new version we now have PivotProperties. There hasn’t been any changes to the number or types of properties. The four available types are :

1. PivotViewerStringProperty
2. PivotViewerNumericProperty
3. PivotViewerDateTimeProperty
4. PivotViewerLinkProperty

PivotViewer has a PivotProperties property (try saying that 3 times fast) that you can set via code or in XAML. For completeness sake, let’s take a look how each would look. Both of these examples yield the same result.

PivotViewer Properties in XAML:

<pivot:PivotViewer x:Name="pViewer">

    <pivot:PivotViewer.PivotProperties>
        <pivot:PivotViewerNumericProperty
            Id="Value"
            Options="None"
            Binding="{Binding Value}"/>
        <pivot:PivotViewerStringProperty
            Id="Data1"
            Options="CanFilter,CanSearchText"
            Binding="{Binding Data1}"/>
        <pivot:PivotViewerStringProperty
            Id="Color"
            Options="CanFilter,CanSearchText"
            Binding="{Binding Color}"/>
        <pivot:PivotViewerDateTimeProperty
            Id="Stamp"
            Options="CanFilter"
            Binding="{Binding Stamp}"/>
    </pivot:PivotViewer.PivotProperties>
</pivot:PivotViewer>


PivotViewer Properties in code behind:


pViewer.PivotProperties = new List<PivotViewerProperty>()

        {
            new PivotViewerNumericProperty()
                {
                    Binding = new Binding("Value"),
                    Id = "Value",
                    Options = PivotViewerPropertyOptions.None
                },
            new PivotViewerStringProperty()
                {
                    Binding = new Binding("Data1"),
                    Id = "Data1",
                    Options = PivotViewerPropertyOptions.CanFilter
                    | PivotViewerPropertyOptions.CanSearchText
                },
            new PivotViewerStringProperty()
                {
                    Binding = new Binding("Color"),
                    Id = "Color",
                    Options = PivotViewerPropertyOptions.CanFilter
                    | PivotViewerPropertyOptions.CanSearchText
                },
            new PivotViewerDateTimeProperty()
                {
                    Binding = new Binding("Stamp"),
                    Id = "Stamp",
                    Options = PivotViewerPropertyOptions.CanFilter
                }

        };

There are only a few options for a PivotProperty, so I thought it would be worth listing them. Here is a break down of each property and how it effects how the PivotProperty is used inside of PivotViewer

PivotProperty Options

None

No options are set

Private

If set, it will not display property in detail pane

CanFilter

Shows the property in the filter pane and the sort drop down box

CanSearchText

The search box will search for this property for matches

Wrapping Text

Will wrap the text within the detail pane


Trading Cards

Now we have our data and have mapped the data to the a collection of PivotProperties, what’s next? The last set it to define what the trading card is going to look like. For this post we are going to look at a basic solution which we will expand upon in the next post.


XAML data templates in PivotViewer take the shape of a PivotViewerItemTemplate. PivotViewer has a ItemTemplates property that is used to map one or more templates for your trading cards. For our case we are going to create a simple trading card that consists of a Border that is filled with the card’s Color property and put a ShortName property in the middle of the Border. The template will look something like this:

<pivot:PivotViewerItemTemplate x:Key="DemoTemplate">
    <Border Width="300" Height="300"
            Background="{Binding Color,
                    Converter={StaticResource colorConverter}}">
        <TextBlock Text="{Binding ShortName}" FontSize="20"
                   HorizontalAlignment="Center"
                   VerticalAlignment="Center" />
    </Border>
</pivot:PivotViewerItemTemplate>

You might notice that I added a value converter to the background. Since we are storing the color as a string, we need to map it to a SolidColorBrush. SL doesn’t expose all of the Color methods you find in .NET, so we have to be a bit clever in getting the color mapped. Here is the value converter that I am using:

public class TextToSolidColorConverter : IValueConverter

{


    public object Convert(object value,
                        Type targetType,
                        object parameter,
                        CultureInfo culture)
    {
        var xaml = "<SolidColorBrush " +
            "xmlns='http://schemas.microsoft.com/client/2007' " +
            "Color=\"" + value.ToString() + "\"/>";
        return XamlReader.Load(xaml);
    }

    public object ConvertBack(object value,
                        Type targetType,
                        object parameter,
                        CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

With our template added as a resource, we can set the template in code with the following:


pViewer.ItemTemplates = new PivotViewerItemTemplateCollection()
    {
        (PivotViewerItemTemplate) Resources["DemoTemplate"]
    };

And that is really all there is to it. If we run our solution, we should get something like this:



European Silverlight 5 Hosting - Amsterdam :: Silverlight 5 Pivot Viewer Control

clock April 16, 2012 09:24 by author Scott

In this article we will learn about creating a Pivot Viewer control in Silverlight .

Lets get started with a short description of what a PivotViewer Control is.


For this example I have used the Silverlight 5 PivotViewer, since most of us would have Silverlight 5 right now .


The Silverlight PivotViewer Control does not come by default with the Silverlight 4 toolkit. It has to be downloaded and installed separately .


With Silverlight 5 one would get the PivotViewer by default .


For Silverlight 4 it must be downloaded from the link shown below :


http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=17747


Once installed , the PivotViewer gets installed in the path as shown below :


C:\Program Files (x86)\Microsoft SDKs\Silverlight\v4.0\PivotViewer\Aug10


Hence forth I am using Silverlight 5 but similar steps needs to be followed for Silverlight 4.


Add a reference to the below DLL as shown below :




Let's start coding then . PivotViewer uses a special type of Collection called as Collection XML .


We need to understand Collection XML in order to effectively work with PivotViewer .


Collection XML (CXML) is the schema used to describe structured data to be displayed in the PivotViewer collection experience.


We make use of a class called CxmlCollectionSource to bind to the ItemSource of the PivotViewer


More Information on the CxmlCollectionSource can be found in the link below :


http://msdn.microsoft.com/en-us/library/system.windows.controls.pivot.cxmlcollectionsource(v=vs.96).aspx


Shown below is how the data is bound to the ItemSource property of the PivotViewer Control .




The final code is below :


            _cxml = new CxmlCollectionSource(new Uri("http://www.xpert360.net/PDC2010/PDC2010.cxml", UriKind.Absolute));

            pv1.PivotProperties = _cxml.ItemProperties.ToList();
            pv1.ItemTemplates = _cxml.ItemTemplates;
            pv1.ItemsSource = _cxml.Items;

Let's give it a run.




Cheers





European Silverlight 5 Hosting - Amsterdam :: Debugging bindings in XAML Silverlight 5

clock March 19, 2012 08:03 by author Scott

One of the cool new tool features in Silverlight 5 is the XAML debugging features. It is limited to debugging bindings in XAML but that is an extremely useful feature.

I have created a demo showing the few steps needed to debug bindings in XAML. The demo consist of a TextBox containing a number a Button to refresh the number. The number is a random number.






The Text property of the TextBox binds to a property called “Number”. It is a Dependency Property defined in my code-behind. To make the binding work I have set the DataContext of the page to its self.




Whenever the Number property is updated it will automatically update the Text value on the TextBox.


As simple as it is I can spend hours looking for errors if I e.g. misspell the property that we use to bind to. Before Silverlight 5 I would get a hint in the Output window if I had a BindingExpression exception. In Silverlight 5 I can add a breakpoint to the binding directly in the XAML.




Debugging the XAML above I get an exception with a BindingExpression path error and enables me to easily identify the error.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in