C# Silverlight – Using Sliders [Beginner]

Being the month of Silverlight, I decided to get off my PHP and JS butt, and learn something new. I am incredibly new to the whole silvery-light thing, but luckily with Visual Studio on your side, it is pretty easy to get things going. I am also using VS2010, which makes the whole experience a grand opening of new stuff for me.
So to begin my foray into Silverlight, I did something easy, but slightly useful at the same time. What I have made is a set of three sliders that represent a RGB value, which in turn changes the color of some text. It is some pretty short code, but it does showcase how to change the color of TextBlock text, which took me a few minutes to find.
[silverlight width=”400″ height=”300″ src=”SilverlightApplication.xap” border=”true”]
To begin with, lets get the XAML out of the way:
<UserControl x:Class="SilverLightColorSliders.Page"
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"
xmlns:basics="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls">

<Grid x:Name="LayoutRoot" Background="White">
<Slider Height="22" Name="redSlider" Width="100" Maximum="255"
ValueChanged="slider_ValueChanged" SmallChange="1"
Margin="145,118,0,0" HorizontalAlignment="Left"
VerticalAlignment="Top" />
<Slider Height="22" HorizontalAlignment="Left" Margin="145,146,0,0"
Name="greenSlider" VerticalAlignment="Top" Width="100" Maximum="255"
ValueChanged="slider_ValueChanged" SmallChange="1" />
<Slider Height="22" HorizontalAlignment="Left" Margin="145,174,0,0"
Name="blueSlider" VerticalAlignment="Top" Width="100" Maximum="255"
ValueChanged="slider_ValueChanged" SmallChange="1" />
<TextBlock Height="30" Margin="96,79,96,191" Name="textBlock1"
Text="Switch on the Code" Width="207" FontSize="20"
HorizontalAlignment="Left" VerticalAlignment="Top" />
<TextBlock Height="21" HorizontalAlignment="Left" Margin="266,118,0,0"
Name="redValue" Text="0" VerticalAlignment="Top" Width="44" />
<TextBlock Height="21" HorizontalAlignment="Left" Margin="266,145,0,0"
Name="greenValue" Text="0" VerticalAlignment="Top" Width="44" />
<TextBlock Height="21" HorizontalAlignment="Left" Margin="266,172,0,0"
Name="blueValue" Text="0" VerticalAlignment="Top" Width="44" />
<TextBlock Height="21" HorizontalAlignment="Left" Margin="80,119,0,0"
Name="redLabel" Text="Red" VerticalAlignment="Top" Width="59"
TextAlignment="Right" />
<TextBlock Height="21" HorizontalAlignment="Left" Margin="80,173,0,0"
Name="blueLabel" Text="Blue" VerticalAlignment="Top" Width="60"
TextAlignment="Right" />
<TextBlock Height="21" HorizontalAlignment="Left" Margin="80,146,0,0"
Name="greenLabel" Text="Green" VerticalAlignment="Top" Width="59"
TextAlignment="Right" />

 
The important things we have here are the sliders and the main “SOTC” label. Of course we have other labels that help us know what we are changing, but essentially all we need are the sliders and the text to recolor. The sliders are set to a max of 255, which is the maximum value for any RGB value.
The key to changing the color of the text inside the TextBlock is an abstract object called a Brush. Since it is abstract, we can’t just use it willy-nilly. Thankfully, C# has objects we can use for exactly what we need to do, in our case a SolidColorBrushobject.
To use this brush, all we need to do is give it a color object with the RGB values we want. The C# Code will end up looking something like so:
    private void slider_ValueChanged(object sender, 
RoutedPropertyChangedEventArgs e)
{
Color textColor = new Color();
textColor
.A = 255;
textColor
.R = (byte)redSlider.Value;
redValue
.Text = Math.Round(redSlider.Value).ToString();
textColor
.G = (byte)greenSlider.Value;
greenValue
.Text = Math.Round(greenSlider.Value).ToString();
textColor
.B = (byte)blueSlider.Value;
blueValue
.Text = Math.Round(blueSlider.Value).ToString();

SolidColorBrush textBrush = new SolidColorBrush(textColor);
textBlock1
.Foreground = textBrush;
}
 
What we want to do is change the color when any of the sliders change their value. So this event is tied to all of the sliders, which makes for great code reuse. What the event is actually doing is quite simple. We create a new C# color object, giving it a full value for alpha. This way there will be no transparency. Next, for each of the three RGB values, we pass it to the color object then display the value in the corresponding TextBlock. Finally we create a SolidColorBrush with the Color object and set the Foreground property of the TextBlock object. The Foregroundproperty is actually a Brush that controls the color of the text inside the TextBlock, so all we have to do is set that property to our Brush object. The end result is text that changes color when we change the color’s value.
Well, that is pretty much all there is to this tutorial. I hope this was informative, and there are sure to be more Silverlight tutorials to come.

C# Silverlight – Using a DataGridTemplateColumn [Beginner]

Whenever you pit designers against developers, it always seems to be the developer that loses. It’s very rare that controls like the Silverlight DataGrid are left alone – designers want little tweaks and polish to increase the user experience. This tutorial is going to illustrate how to use one of the most flexible solutions to theming a DataGrid – the DataGridTemplateColumn.
We’ll be touching very little on the basics of how to use the Silverlight DataGrid. If you’re new to the control.
The first thing we’re going to do is build a default DataGrid without any styling. I created a class to hold some information about the SOTC authors and bound a collection of those to my DataGrid.
[silverlight width=”400″ height=”300″ src=”BasicDataGrid.xap”]
using System.Collections.Generic;
using System.Windows.Controls;

namespace DataGridStyling
{
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();

// Create some authors.
List authors = new List()
{
new Author()
{
Name = "Brandon",
Username = "The Reddest",
Language = "C#"
},
new Author()
{
Name = "Charlie",
Username = "The Fattest",
Language = "ActionScript"
},
new Author()
{
Name = "Richard",
Username = "The Hairiest",
Language = "PHP"
},
new Author()
{
Name = "Mike",
Username = "The Tallest",
Language = "JavaScript"
}
};

// Set the items source on the DataGrid to the
// collection of authors.
_dataGrid.ItemsSource = authors;
}
}

///
/// Class to hold some information about an
/// SOTC author.
///

public class Author
{
public string Name { get; set; }
public string Username { get; set; }
public string Language { get; set; }
}
}

<UserControl x:Class="DataGridStyling.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dg="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
Width="400" Height="300">

<dg:DataGrid x:Name="_dataGrid"
AutoGenerateColumns="False">

<dg:DataGridTextColumn
Binding="{Binding Name}"
Header="Name"
Width="100" />
<dg:DataGridTextColumn
Binding="{Binding Username}"
Header="Username"
Width="100" />
<dg:DataGridTextColumn
Binding="{Binding Language}"
Header="Language"
Width="100" />



 
All right, now let’s starting using the DataGridTemplateColumn. This column type gives us the ability to set the template for normal cells and cells that are in edit mode. Here’s the same example as above except that uses this column type on the Name column.
[silverlight width=”400″ height=”300″ src=”TemplateColumn.xap”]
<dg:DataGrid x:Name="_dataGrid" 
AutoGenerateColumns="False">

<dg:DataGridTemplateColumn
Header="Name"
Width="100">


<TextBlock Text="{Binding Name}"
Foreground="Green"
FontWeight="Bold"
VerticalAlignment="Center"/>








<dg:DataGridTextColumn
Binding="{Binding Username}"
Header="Username"
Width="100" />
<dg:DataGridTextColumn
Binding="{Binding Language}"
Header="Language"
Width="100" />

 
So as you can see, we changed the cell to display bold green text when not in edit mode, and a simple TextBox when it is in edit mode. This is accomplished by using the CellTemplate and CellEditingTemplateproperties on the DataGridTemplateColumn object. I had to explicitly set the BindingModeto TwoWay so text entered into the TextBox would be committed back to my Author object.
Here’s a slightly more interesting example that builds on the previous one. Now, whenever edit mode is entered, a pencil icon will be displayed to the left of the edit field.
[silverlight width=”400″ height=”300″ src=”Pencil.xap”]
<dg:DataGrid x:Name="_dataGrid" 
AutoGenerateColumns="False">

<dg:DataGridTemplateColumn
Header="Name"
Width="100">


<TextBlock Text="{Binding Name}"
Foreground="Green"
FontWeight="Bold"
VerticalAlignment="Center"/>









<Image Source="pencil_icon.png"
Grid.Column="0" />
<TextBox Text="{Binding Name, Mode=TwoWay}"
Grid.Column="1" />




<dg:DataGridTextColumn
Binding="{Binding Username}"
Header="Username"
Width="100" />
<dg:DataGridTextColumn
Binding="{Binding Language}"
Header="Language"
Width="100" />

 
All I had to do in order to use the pencil icon was add it to my project like you would any other existing item. By default the Build Action property on the image will be set to Resource, which is what you want. Now, in XAML, you can simply reference the image by name.
There are basically no limits to how you can display information within cells using this column type. The powerful templating system behind Silverlight and WPF makes doing stuff like this trivial whereas before it may not have even been possible to accomplish the same task. On that note, that wraps up this introduction to the DataGridTemplateColumn.

C# Silverlight – Loading a Client Side Image [Beginner]

Since the RTW (release to web) of Silverlight 2 was just the other day, I decided to take a look and see if this problem still existed.
And what do you know! Not only is it possible, it is downright easy. You can load images from any stream, which means it could be a file stream from isolated storage, a file that the user just chose in an Open File Dialog, or even over the web using stuff like OpenReadAsync (on the WebClient class. Below, you can see the small example app that shows this off – you can pick any image file on your computer, and Silverlight can display it right there for you.
[silverlight width=”400″ height=”300″ border=”true” src=”Silverlight2ImageLoading.xap”]
This is going to be a short tutorial, because really there isn’t much code behind it. So let’s jump straight into the XAML:
<UserControl x:Class="Silverlight2ImageLoading.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300" Background="White">









<TextBlock Grid.Row="0" Grid.Column="0"
VerticalAlignment="Center"
HorizontalAlignment="Center"
x:Name="Message">
Choose An Image

<Button Grid.Row="0" Grid.Column="1"
Content="Browse..." Click="BrowseClick" />
<Image Margin="3" x:Name="ImageHolder"
Grid.ColumnSpan="2" Grid.Row="1"
Grid.Column="0" Stretch="UniformToFill" />

 
Nothing terribly special here – just a grid with two rows and two columns. The first row holds a textblock we will use for messages and a button whose click event actually does all the interesting work. The second row holds an image with no source set, so when the app loads initially nothing will be displayed there. It is this image control that will get populated with whatever image the user chooses.
Now for the C# code behind:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

namespace Silverlight2ImageLoading
{
public partial class Page : UserControl
{
public Page()
{ InitializeComponent(); }

private void BrowseClick(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = false;
bool? result = ofd.ShowDialog();
if (!result.HasValue || result.Value == false)
return;

BitmapImage imageSource = new BitmapImage();
try
{
imageSource.SetSource(ofd.File.OpenRead());
ImageHolder.Source = imageSource;
Message.Text = "Showing " + ofd.File.Name;
}
catch (Exception)
{
Message.Text = "Error Loading File";
}
}
}
}
 
As I mentioned above, the meat of this code is all in the handler for that button – the method BrowseClick. First, we create an OpenFileDialog. This is not your normal OpenFileDialog – this is one specially created for Silverlight that keeps any silverlight applications from doing anything malicious. And unlike the old OpenFileDialog, this one does not return a DialogResult, it just returns a nullable boolean. If the boolean value is true, then the user has selected something and clicked ok in the dialog.
So once the user has selected something, we want to load an image from that file. To do that, we first create a BitmapImage, which will become the source for our image control. Just as a quick note, BitmapImage is in System.Windows.Media.Imaging, which is not one of the default using statement lines, so don’t forget to add that in. Once we have created the BitmapImage we call the SetSource method and hand it the stream from whatever file the user selected in the open file dialog. If anything is wrong with the file (i.e, it is not an image, it can’t be read, etc..), an exception will be thrown, which is why those couple lines of code are wrapped in a try-catch.
If the SetSource call succeeds, we then set that BitmapImage as the new Source for our image, and we set the text of that message TextBlock to the name of the file. If stuff fails and an exception gets thrown, we just set that TextBlock to an error message.
And that’s all folks! As we here play more around with the RTW version of Silverlight 2, we will be posting more tutorials (and hopefully posting new versions of some now old and obsolete Silverlight 1.1 tutorials). As always, questions or comments are welcome.