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 :: 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 :: Implicit Data Templates in Silverlight 5

clock May 29, 2012 08:43 by author Scott

One of the powerful new features around templating in the Silverlight 5 beta is the ability to produce a DataTemplate that will be implicitly associated with a particular data type.

For example, if I have these 2 simple types Person and Vehicle;


public class Person  
{  
  public string FirstName { get; set; }  
  public string LastName { get; set; }  
  public int Age { get; set; }  
}  
public class Vehicle  
{  
  public string Type { get; set; }  
  public int Wheels { get; set; }  
}
 

then I can define implicit templates for them by writing templates such as these;


<UserControl.Resources> 
    <DataTemplate 
      DataType="local:Person"> 
      <StackPanel> 
        <TextBlock 
          Text="{Binding FirstName}" /> 
        <TextBlock 
          Text="{Binding LastName}" /> 
        <TextBlock 
          Text="{Binding Age}" /> 
      </StackPanel> 
    </DataTemplate> 
    <DataTemplate 
      DataType="local:Vehicle"> 
      <StackPanel> 
        <TextBlock 
          Text="{Binding Type}" /> 
        <TextBlock 
          Text="{Binding Wheels}" /> 
      </StackPanel> 
    </DataTemplate> 
  </UserControl.Resources>
 

where I have not specified a
Key for these resources but have, instead, specified a DataType and that’s enough for Silverlight to figure it out.

If I have a scenario like this one where I have a
ListBox bound to a set of Items;

<Grid>  
  <Grid.RowDefinitions>  
    <RowDefinition />  
    <RowDefinition  
      Height="Auto" />  
    <RowDefinition  
      Height="Auto" />  
  </Grid.RowDefinitions>  
  <ListBox  
    ItemsSource="{Binding Items}">  
  </ListBox>  
  <Button  
    Command="{Binding AddPerson}" 
    Content="Add Person" 
    Grid.Row="1" />  
  <Button  
    Command="{Binding AddVehicle}" 
    Content="Add Vehicle" 
    Grid.Row="2" />  
</Grid> 


with a
DataContext providing a view model like this one;

public class ViewModel  
{  
  public ViewModel()  
  {  
    this.Items = new ObservableCollection<object>();  
    this.AddPerson = new SimpleCommand(() =>  
      {  
        this.Items.Add(  
          new Person()  
          {  
            FirstName = "TestFirst",  
            LastName = "TestLast",  
            Age = 22  
          });  
      });  
    this.AddVehicle = new SimpleCommand(() =>  
      {  
        this.Items.Add(  
          new Vehicle()  
          {  
            Type = "Car",  
            Wheels = 4  
          });  
      });  
  }  
  public ObservableCollection<object> Items { get; set; }  
  public ICommand AddPerson { get; set; }  
  public ICommand AddVehicle { get; set; }  
}
 

then whenever I add a
Person to the ListBox the runtime will find the right implicit template to display the Person and if I add a Vehicle to the ListBox then the runtime will do the right thing there too;



and, if for example I was to make my ViewModel implement property change notification and then bind up a new property called
SelectedItem to my ListBox then I can bring in a ContentPresenter and it will also make use of the implicit template as in;

<UserControl.Resources>  

  <DataTemplate  
    DataType="local:Person">  
    <StackPanel>  
      <TextBlock  
        Text="{Binding FirstName}" />  
      <TextBlock  
        Text="{Binding LastName}" />  
      <TextBlock  
        Text="{Binding Age}" />  
    </StackPanel>  
  </DataTemplate>  
  <DataTemplate  
    DataType="local:Vehicle">  
    <StackPanel>  
      <TextBlock  
        Text="{Binding Type}" />  
      <TextBlock  
        Text="{Binding Wheels}" />  
    </StackPanel>  
  </DataTemplate>  
</UserControl.Resources>  

<UserControl.DataContext>  

  <local:ViewModel />  
</UserControl.DataContext>  

<Grid>  

  <Grid.ColumnDefinitions>  
    <ColumnDefinition />  
    <ColumnDefinition />  
  </Grid.ColumnDefinitions>  
  <Grid.RowDefinitions>  
    <RowDefinition />  
    <RowDefinition  
      Height="Auto" />  
    <RowDefinition  
      Height="Auto" />  
  </Grid.RowDefinitions>  
  <ListBox  
    ItemsSource="{Binding Items}" 
    SelectedValue="{Binding SelectedItem,Mode=TwoWay}" />  
  <Button  
    Command="{Binding AddPerson}" 
    Content="Add Person" 
    Grid.Row="1" />  
  <Button  
    Command="{Binding AddVehicle}" 
    Content="Add Vehicle" 
    Grid.Row="2" />  
  <ContentPresenter  
    Grid.Column="1" 
    Content="{Binding SelectedItem}" />  
</Grid> 


and so then both the ListBox on the left and the ContentPresenter on the right are using implicit templates to display content;




(as an aside, I also tried this with a
ContentPresenter inside a Tooltip and it didn’t work for me so far in the beta).

Naturally, you can override these implicit templates so if I want a different template for my
ContentPresenter I can simply add an implicit template that is nearer to the ContentPresenter in the hierarchy of resource resolution as in;

<UserControl.Resources> 

  <DataTemplate 
    DataType="local:Person"> 
    <StackPanel> 
      <TextBlock 
        Text="{Binding FirstName}" /> 
      <TextBlock 
        Text="{Binding LastName}" /> 
      <TextBlock 
        Text="{Binding Age}" /> 
    </StackPanel> 
  </DataTemplate> 
  <DataTemplate 
    DataType="local:Vehicle"> 
    <StackPanel> 
      <TextBlock 
        Text="{Binding Type}" /> 
      <TextBlock 
        Text="{Binding Wheels}" /> 
    </StackPanel> 
  </DataTemplate> 
</UserControl.Resources> 

<UserControl.DataContext> 

  <local:ViewModel /> 
</UserControl.DataContext> 

<Grid> 

  <Grid.ColumnDefinitions> 
    <ColumnDefinition /> 
    <ColumnDefinition /> 
  </Grid.ColumnDefinitions> 
  <Grid.RowDefinitions> 
    <RowDefinition /> 
    <RowDefinition 
      Height="Auto" /> 
    <RowDefinition 
      Height="Auto" /> 
  </Grid.RowDefinitions> 
  <ListBox 
    ItemsSource="{Binding Items}" 
    SelectedValue="{Binding SelectedItem,Mode=TwoWay}" /> 
  <Button 
    Command="{Binding AddPerson}" 
    Content="Add Person" 
    Grid.Row="1" /> 
  <Button 
    Command="{Binding AddVehicle}" 
    Content="Add Vehicle" 
    Grid.Row="2" /> 
  <Grid 
    Grid.Column="1"> 
    <Grid.Resources> 
      <DataTemplate 
        DataType="local:Vehicle"> 
        <StackPanel 
          Orientation="Horizontal"> 
          <TextBlock 
            Text="{Binding Type}" /> 
          <TextBlock 
            Text="{Binding Wheels}" /> 
        </StackPanel> 
      </DataTemplate> 
    </Grid.Resources> 
    <ContentPresenter 
        Grid.Column="1" 
        Content="{Binding SelectedItem}"/> 
  </Grid> 
</Grid> 

and, naturally, you can also mix/match this implicit approach with the explicit approach that you’d use in Silverlight 4 today.


I think this is a pretty powerful addition to the Silverlight 5 binding/templating abilities and it’ll be interesting to see what other folks and frameworks do with it.

 



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.



European Silverlight 5 Hosting - Amsterdam :: Using the DatePicker control in Silverlight 5

clock March 5, 2012 07:27 by author Scott

This article introduces the DatePicker control present in the Silverlight Toolkit and shows how to use it in Silverlight applications.

The DatePicker control enables users to select dates using a Calendar like interface. It also includes a TextBox as part of its interface so that users can enter a date instead of selecting one from the Calendar.


The DatePicker control is not part of the Silverlight runtime, it is available in the Silverlight SDK. To use a control from the Silverlight SDK, you must add a reference to the assembly and include the appropriate XML namespace mapping in XAML.


For example,


xmlns
:sdk=http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk

Let us see how to use this control.


Create a new Silverlight 5 application named SilverlightDemo.


You can see the DatePicker control in the Toolbox.




Add the DatePicker control from the Toolbox into your application between the <Grid></Grid> tags.


The XAML markup will look as follows:


<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">

<sdk:DatePicker Height="23" HorizontalAlignment="Left" Margin="49,77,0,0" Name="datePicker1" VerticalAlignment="Top" Width="120" />

</Grid>

</UserControl>


Save, build, and execute the application. Click the calendar icon next to the Textbox in the DatePicker.




The default date format of the The DatePicker control is M/dd/yyyy. To change the format, you either use the SelectedDateFormat property which allows one of two values: Long or Short, or set the current culture of the thread to a new culture, which will also affect the date format. You can also change number of properties of this control.




Add a TextBox and a Button control to the page and configure the XAML markup as follows:


<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">

<TextBox x:Name="txtDate" Height="20" Margin="49,124,182,156" Width="99"/>

<sdk:DatePicker Height="23" HorizontalAlignment="Left" Margin="49,77,0,0" Name="datePicker1" VerticalAlignment="Top" Width="120" DisplayDateEnd="11/26/2012" SelectionBackground="#FFE83333" FontFamily="Georgia" FontSize="14" DisplayDateStart="{Binding Text, ElementName=txtDate, Mode=TwoWay}" />

<Button Height="25" Margin="40,167,169,108" Width="94" Content="OK"/>

</Grid>

</UserControl>


This markup sets the start date, end date, font style, selection background color, and binds the content of the text box to the DatePicker.

Some of the commonly used properties of the DatePicker control are:

Property

Description

BlackoutDates

Retrieves or assigns a collection of dates that are blacked out or unselectable

CalendarStyle

Retrieves or assigns the style that is used when rendering the calendar

DisplayDate

Retrieves or assigns the date to be displayed

DisplayDateEnd

Retrieves or assigns the beginning date in the calendar

DisplayDateStart

Retrieves or assigns the end date in the calendar

FirstDayOfWeek

Retrieves or assigns the day that is considered the beginning of the week

IsDropDownOpen

Retrieves or assigns a value that indicates whether the drop-down Calendar is open or closed

IsTodayHighlighted

Retrieves or assigns a value that indicates whether the current date is highlighted

SelectedDate

Retrieves or assigns the selected date

SelectedDateFormat

Retrieves or assigns the format that is used to display the selected date

SelectionBackground

Retrieves or assigns the background used for selected dates

 



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