Mar 25

I am going to show you how you can modify the standard ListBox control used in Silverlight 2.0. Many people want to change the default view of this control but they can’t remove the line between the items. If you download the code of the Silverlight control from the official site of Microsoft you will see that after every item there is a line. In this example I will show you how you can remove this line.

Let’s create e new Silverlight 2.0 application and place a ListBox in it.

<ListBox>
    <ListBox.Items>
    <ListBoxItem Content="I am the first item in the collection" />
    <ListBoxItem Content="I am the second item in the collection" />
  </ListBox.Items>
 </ListBox>

In order to change the default look of our items we have to modify the ItemContainerStyle property of out ListBox control.

<ListBox.ItemContainerStyle>
  <Style TargetType="ListBoxItem">
    <Setter Property="Background" Value="LightBlue" />
    <Setter Property="Template"></Setter>
  </Style>
</ListBox.ItemContainerStyle>

Template contains the style of each item in the ListBox. If you look at the generics.xaml (the source file of the controls) you will see how it is created by default. We will replace this style by creating a new one: each item will contains a ellipse and a text after it. That’s why we are going to create a Grid with two columns: first of them will contain the ellipse and the second one - the textblock

<Setter Property="Template">
  <Setter.Value>
    <ControlTemplate TargetType="ListBoxItem">
      <Grid x:Name="RootElement" Background="{TemplateBinding Background}">
        <Grid.RowDefinitions>
          <RowDefinition Height="*"/>
          <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="30" />
          <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>      

        <Ellipse Fill="Blue" Stroke="White" StrokeThickness="1" Grid.Column="0" Margin="3" />

        <ContentPresenter Grid.Column="1" Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}" Margin="3" />
      </Grid>
    </ControlTemplate>
  </Setter.Value>
</Setter>

And that’s it! We have our ListBox control modified! If you see there is no indication when you have selected an item. This is because we have not provided Storyboards for this. You can see in the sorce of this control how it is implemented and you can then easily modify it.

Silverlight ListBox Control Modified

Mar 7

SilverlightIn MIX Conference 2008 Microsoft presented Silverlight 2.0 beta 1. Here is a list of new features in this release:

  • WPF UI Framework
    Silverlight 2 includes a rich WPF-based UI framework that makes building rich Web applications much easier. In includes a powerful graphics and animation engine, as well as rich support for higher-level UI capabilities like controls, layout management, data-binding, styles, and template skinning. The WPF UI Framework in Silverlight is a compatible subset of the WPF UI Framework features in the full .NET Framework, and enables developers to re-use skills, controls, code and content to build both rich cross browser web applications, as well as rich desktop Windows applications.
  • Rich Controls
    Silverlight 2 includes a rich set of built-in controls that developers and designers can use to quickly build applications. This upcoming Beta1 release includes core form controls (TextBox, CheckBox, RadioButton, etc), built-in layout management panels (StackPanel, Grid, Panel, etc), common functionality controls (Slider, ScrollViewer, Calendar, DatePicker, etc), and data manipulation controls (DataGrid, ListBox, etc). The built-in controls support a rich control templating model, which enables developers and designers to collaborate together to build highly polished solutions.
  • Rich Networking Support
    Silverlight 2 includes rich networking support. It includes out of the box support for calling REST, WS*/SOAP, POX, RSS, and standard HTTP services. It supports cross domain network access (enabling Silverlight clients to directly access resources and data from resources on the web). Beta1 also includes built-in sockets networking support.
  • Rich Base Class Library
    Silverlight 2 includes a rich .NET base class library of functionality (collections, IO, generics, threading, globalization, XML, local storage, etc). It includes rich APIs that enable HTML DOM/JavaScript integration with .NET code. It also includes LINQ and LINQ to XML library support (enabling easy transformation and querying of data), as well as local data caching and storage support. The .NET APIs in Silverlight are a compatible subset of the full .NET Framework.

The SDK for Silverlight 2.0 beta 1 is already available at its website.

Mar 2
Lambda Expressions
icon1 Boyan Mihailov | icon2 C# | icon4 03 2nd, 2008| icon3No Comments »

In C# 2.0 there are anonymous methods, which allows you to write your method code inline instead of creating a new method in your class. In C# 3.0 there is a new feature - lambda expressions. The goal of this expressions is the same as the anonymous methods, but the syntax is more concise.

Let’s have the following code:

class LambdaExpressionTest
{
  public delegate int myDelegate(int x);

  static void Main()
  {
    myDelegate testFunc = new myDelegate(LambdaExpressionTest.myFucn);
    Console.WriteLine(testFunc(5)); // returns 23
  }

  public static int myFucn(int x) { return x * x - 2; }
}

If we want to rewrite this code using anonymous method, it will get the following look:

class LambdaExpressionTest
{
  public delegate int myDelegate(int x);

  static void Main()
  {
    myDelegate testFunc = new myDelegate(delegate(int x) { return x * x - 2; });
    Console.WriteLine(testFunc(5));
  }
}

And if we want to rewrite this code using lambda expressions, it will look like this:

class LambdaExpressionTest
{
  public delegate int myDelegate(int x);

  static void Main()
  {
    myDelegate testFunc = x => x * x - 2;
    Console.WriteLine(testFunc(5));
  }
}

Isn’t it so simple? :) The sign ‘=>‘ is read as “goes to”. We first indicate the arguments of our method and after that we do our calculations in it.

Feb 23
Xml Serialization
icon1 Boyan Mihailov | icon2 C# | icon4 02 23rd, 2008| icon3No Comments »

If you want to store data, you often use a database. It’s very good way. But, sometimes you need to save too little amount of data that using a database is thoughtless. Another way to store data is to put it in a simple text file. One of the most convenient ways to do this is to use a XML file. It stores data in such a way, that you can easily access it later. XML files are used everywhere and for every type of usage. For example, two (or more) computers can communicate with XML files.

I am going to show you how you can convert your object to a XML file in order to save its data. This process if called serialization. There are many ways to serialize an object. I am going to show you how you can you do this by using the IXmlSerializable interface. It’s in System.Xml.Serialization namespace. You’ll need to include System.Xml namespace, too.

If you look at the source of this interface, you will probably see something like this:

interface IXmlSerializable
{
  System.Xml.Schema.XmlSchema GetSchema ();
  void ReadXml (System.Xml.XmlReader reader);
  void WriteXml (System.Xml.XmlWriter writer);
}

The first method returns an object of type XmlSchema. It determines the schema of your future XML file. In our case, we won’t change this schema and our file will have the standard one. WriteXml method uses a XmlWriter object to determine what data and in what way will be stored in the file. ReadXml reads the file (by an XmlReader object) and changes the properties of your object depending of the read information.

Here’s our simple class that we will use:

public class Test
{
  private int id;
  private string value;

  public int Id
  {
    get { return this.id; }
    set { this.id = value; }
  }

  public string Value
  {
    get { return this.value; }
    set { this.value = value; }
  }

  public Test() : this(0, string.Empty) { }

  public Test(int id, string value)
  {
    Id = id;
    Value = value;
  }
}

Inheriting the IXmlSerializable interface, you should define its three methods. As we said earlier, we are not going to change the default XmlSchema, so this method will return null. In this case we have only to properties to store. Here is the proper way to do this:

public void WriteXml(XmlWriter writer)
{
  writer.WriteElementString("Id", Id.ToString());
  writer.WriteElementString("Value", Value);
}

Before showing how to implement the ReadXml method, I want to show you the real usage - how to serialize this object. Using the XmlSerializer object, we can do this. I want to say, that for the sake of serialization, your class must have a parameterless constructor!

Test test = new Test(1, "myVeryImportantData");
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Test));

using (XmlTextWriter xmlWriter = new XmlTextWriter("c:\\test.xml", Encoding.UTF8))
{
  xmlWriter.Formatting = Formatting.Indented;
  xmlSerializer.Serialize(xmlWriter, test);
}

This example creates the following XML file:

<?xml version="1.0" encoding="utf-8"?>
<test>
  <id>1</id>
  <value>myVeryImportantData</value>
</test>

Now, in order to restore our object by this information in our XML file, we have to deserialize it by implementing the ReadXml method. We know the structure of the file, so it’s very easy.

public void ReadXml(XmlReader reader)
{
  reader.ReadStartElement();
  reader.ReadStartElement("Id");
  Id = reader.ReadContentAsInt();
  reader.ReadEndElement();
  reader.ReadStartElement("Value");
  Value = reader.ReadString();
  reader.ReadEndElement();
}

Now, we are ready. The final step to reconstruct our object are here:

Test deserializedObject = null;

using (XmlTextReader xmlReader = new XmlTextReader("c:\\test.xml"))
{
  deserializedObject = (Test)xmlSerializer.Deserialize(xmlReader);
}
Console.WriteLine(deserializedObject.Value);

That’s it! Very nice! Using this interface, we can easily serialize whatever type of object and then to deserialize it.

Feb 22
Simple Gradient
icon1 Boyan Mihailov | icon2 C# | icon4 02 22nd, 2008| icon3No Comments »

A simple was how to draw a gradient on a form. All you need is to include both Drawing and Drawing2D namespaces in your project. As we are going to draw onto the form, we need to assure, that if user resizes it, we will have our gradient spread over the whole form. We can do this by using form’s Resize event. Each time the form is being resized, we tell it to repaint.

private void Form1_Resize(object sender, EventArgs e)
{
  this.Invalidate();
}

In order to paint on the form, we are going to use its Paint event. In this way, the next time a message to repaint is received, we will have our gradient repainted.

The class LinearGradientBrush creates a special brush, which we can use in our further work. It accepts four arguments:

  1. a rectangle, which determines the area where we are going to paint
  2. color one
  3. color two
  4. an angle

Here is a simple example.

private void Form1_Paint(object sender, PaintEventArgs e)
{
  e.Graphics.Clip = new Region(ClientRectangle);
  LinearGradientBrush gradient = new LinearGradientBrush(ClientRectangle, Color.Peru, Color.Pink, 90f);
  e.Graphics.SmoothingMode = SmoothingMode.HighQuality; // set the quality
  e.Graphics.FillRectangle(gradient, ClientRectangle);

  gradient.Dispose();
}

Gradient

« Previous Entries