Element to Element Binding in Silver Light 3.0

Objective

This article I am going to discuss new feature of SilverLight3.0 called Element to Element Binding. I will discuss three samples to understand Element to Element Binding.

Example

I will take an example to explain Element to Element binding. I will bind value of slider control to text of a text block. First I will bind using ValueChanged event of slider control (Sample #1) then I will move to accomplish same task using Element to Element Binding (Sample#2)

Element to Element Binding

This is a new feature provided by Silver Light 3.0. This allows one element to bind other element’s property. This feature is very useful when you want to tie two objects such that when value of one objects changes it got reflected in other object’s value.

Sample #1 [Event Handler Approach]

  1. Take a Stack Panel
  2. Create one Text Block and one Slider inside Stack Panel.
<UserControl x:Class=”ElementBindingDemo.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&#8243; xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006

 mc:Ignorable=”d” d:DesignWidth=”640″ d:DesignHeight=”480″>
<Grid x:Name=”LayoutRoot” Background=”Aqua”>

 <Grid.RowDefinitions>
<RowDefinition Height=” 1*” />
<RowDefinition Height=” 1*” />
</Grid.RowDefinitions>
<StackPanel x:Name=”topStkPanel” HorizontalAlignment=”Stretch” VerticalAlignment=”Stretch” Grid.Row=”0″ Orientation=”Vertical”>
<Slider x:Name=”topSlider” Width=”200″ Height=”200″ Maximum=”100.0″ Minimum=”0″ Value=”50″ HorizontalAlignment=”Center”/>
<TextBlock x:Name=”topTextBlock” Height=”Auto” Width=”Auto” FontFamily=”Georgia” FontSize=”18″ HorizontalAlignment=”Center”
Text=”20″/>
</StackPanel>
</Grid></UserControl>

  1. Add event handler for ValueChanged of slider
  2. Assign value of slider to text of text box while handling the event ValueChanged
namespace ElementBindingDemo

{

public partial class MainPage : UserControl{
public MainPage(){
InitializeComponent();
topSlider.ValueChanged += new
RoutedPropertyChangedEventHandler<double>(topSlider_ValueChanged);
}
void topSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
topTextBlock.Text = topSlider.Value.ToString();}}}

Problem with above approach

If we need to bind one slider control then above approach is fine but imagine if we need to bind many elements value to other elements value. In that scenario event handler approach is not quiet ok. So in Silver Light3.0 we got Element to Element Binding.

Sample #2 [Element to Element Binding]

This is new way of binding introduced in Silver Light 3.0. This is called Element to Element Binding. The best part of this approach is that rather than binding a property , we could bind an element to other element.

Element binding is done as; where bottomSlider is name of the element we are binding to text of text block.

Text=”{Binding Value,Mode=OneWay, ElementName=bottomSlider }


<StackPanel x:Name=”topStkPane2″ HorizontalAlignment=”Stretch” VerticalAlignment=”Stretch” Grid.Row=”1″ Orientation=”Vertical”>
<Slider x:Name=”bottomSlider” Width=”200″ Height=”200″ Maximum=”100.0″ Minimum=”0″ Value=”50″/>

<TextBlock x:Name=”bottomTextBlock” Height=”Auto” Width=”Auto” FontFamily=”Georgia” FontSize=”18″ HorizontalAlignment=”Center”
Text=”{Binding Value,Mode=OneWay, ElementName=bottomSlider }”/>

</StackPanel>

So we do not need any event handler in place for binding.

Sample #3

Binding image width and height value with slider value.

In this sample I will add textbox with Event approach and height and width of image with Element to Element binding approach.

MainPage.Xaml

<UserControl x:Class=”ElementBindingDemo.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&#8243; xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006
mc:Ignorable=”d” d:DesignWidth=”640″ d:DesignHeight=”480″>

<Grid x:Name=”LayoutRoot” Background=”Aqua” Height=”Auto” Width=”Auto”>
<Grid.RowDefinitions>

<RowDefinition Height=”Auto”/>

</Grid.RowDefinitions>

<StackPanel x:Name=”topStkPanel” HorizontalAlignment=”Stretch” VerticalAlignment=”Stretch” Grid.Row=”0″ Orientation=”Vertical” >
<Slider x:Name=”topSlider” Width=”200″ Height=”200″ Maximum=”1000.0″ Minimum=”100.0″ Value=”50″ HorizontalAlignment=”Center”/>
<TextBlock x:Name=”topTextBlock” Height=”Auto” Width=”Auto” FontFamily=”Georgia” FontSize=”18″ HorizontalAlignment=”Center”
Text=”20″/>

<Image Source=”a.jpg” Width=”{Binding Value , ElementName=topSlider}” Height=”{Binding Value , ElementName=topSlider}”></Image>

</StackPanel>

</Grid>
</UserControl>

MainPage.Xaml.cs


using System;

using System.Collections.Generic;using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

namespace ElementBindingDemo{
public partial class MainPage : UserControl{
public MainPage()
{
InitializeComponent();
topSlider.ValueChanged += newRoutedPropertyChangedEventHandler<double>(topSlider_ValueChanged);
}
void topSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e){
topTextBlock.Text = topSlider.Value.ToString();}}}

Conclusion

In this article, I showed three samples on element to element binding. Thanks for reading.

File Handling in Isolated Storage in Silver Light

Objective

This article will explain,

  1. How to create a text file in IsolatedStorageFile of a SilverLight 2 application.
  2. How to write into a text file in IsoltaedStorageFile.
  3. How to read a text file from IsolatedStorageFile.
  4. How to delete a file from IsolatedStorageFile.

Step 1

Create a SilverLight application. By selecting File->New->Project->SilverLight-> SilverLight Application.Design the XAML page. I am creating three buttons for the purpose of Read, Write and Delete File. There are two text boxes. One to get filename input and other for displaying content from the file and saving content from that text box.

MainPage.Xaml

<UserControl
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&#8243; ns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006&#8243; x:Class=”FileReadingandWritingwithIsolatedStorage.MainPage”
Width=”Auto” Height=”Auto” mc:Ignorable=”d”><Grid x:Name=”LayoutRoot” Height=”400″ Width=”600″>

   <Grid.Background>

 <LinearGradientBrush EndPoint=”0.5,1″ StartPoint=”0.5,0″>
 <GradientStop Color=”#FF000000″/>
<GradientStop Color=”#FFE9DDDD” Offset=”1″/>
</LinearGradientBrush>
</Grid.Background><Grid.RowDefinitions>
<RowDefinition Height=”0.175*”/> <RowDefinition Height=”0.182*”/>  <RowDefinition Height=”0.642*”/>
 </Grid.RowDefinitions>
<TextBox x:Name=”txtFileLabel” HorizontalAlignment=”Left” Margin=”17,18,0,17″ Width=”188″ FontSize=”18″ FontWeight=”Normal” Text=”File Name” TextWrapping=”Wrap” Opacity=”0.3″ Background=”#FF808080″/>
 <TextBox x:Name=”txtFileName” Margin=”252,18,48,17″ Width=”300″ FontSize=”18″ FontWeight=”Bold” Text=”” TextWrapping=”Wrap”/>
<Button x:Name=”btnRead” HorizontalAlignment=”Left” Margin=”17,23,0,8″ Width=”180″ FontSize=”18″ FontWeight=”Bold” Grid.Row=”1″ Content=”Read” Click=”btnRead_Click”/>
<Button x:Name=”btnWrite” Margin=”0,23,36,8″ Width=”180″ FontSize=”18″ FontWeight=”Bold” Grid.Row=”1″ Content=”Write” Click=”btnWrite_Click” d:LayoutOverrides=”Width” HorizontalAlignment=”Right”/>
 <TextBox x:Name=”txtContent” Margin=”30,22,45,34″ Grid.Row=”2″ Text=”” TextWrapping=”Wrap” FontSize=”9″/>
<Button x:Name=”btnDelete” Margin=”235,23,251,8″ Grid.Row=”1″ Content=”Delete File” FontWeight=”Bold” FontSize=”18″ Click=”btnDelete_Click”/>
</Grid>
</UserControl>

 Step 2
Now, writing the code behind to handle the Read and Write Operation. I am using IsolatedStorageFIle class to perform file handling operations.
IsolatedStorageFile

  1. This class is inside the namespace System.IO.IsolatedStorage
  2. We could set domain of IsolatedStorageFile either for SilverLight website or for SilverLight Application.
  3. There are many methods exist inside this to work with File operations. For example, create directory, create file, delete directory, delete file etc. 

How to write into the file?

private void btnWrite_Click(object sender, System.Windows.RoutedEventArgs e){using (var store = IsolatedStorageFile.GetUserStoreForApplication(){
if (!(store.FileExists(txtFileName.Text))){
MessageBox.Show(“File does not exist , we are creating one for you “);
IsolatedStorageFileStream file = store.CreateFile(txtFileName.Text);
file.Close();}
using (StreamWriter sw = new StreamWriter(store.OpenFile(txtFileName.Text, FileMode.Open, FileAccess.Write)))
{
sw.WriteLine(txtContent.Text);
}
txtContent.Text = “”;

txtFileName.Text = “”;
MessageBox.Show(“File Writen”);}}

 Explanation

  1. StreamWriter is being used to write into the file.
  2. StreamWriter is inside the namespace System.IO.
  3. We are opening the ISolatedStorageFile for the SilverLight Application.
  4. We are checking, that if file name provided by user does not exist then create a new one with the provided name.
  5. We are opening the file in Write Mode and writing the stream into that.

     How to Read from the file?

private void btnRead_Click(object sender, System.Windows.RoutedEventArgs e){using (var store = IsolatedStorageFile.GetUserStoreForApplication(){
if (!(store.FileExists(txtFileName.Text))){
MessageBox.Show(“File does not exist “);
txtFileName.Text = “”;
}
else{
using (StreamReader sr = new StreamReader(store.OpenFile(txtFileName.Text, FileMode.Open, FileAccess.ReadWrite))) {
txtContent.Text = sr.ReadToEnd();
}}}}

Explanation

  1. StreamReader is being used to read from the file.
  2. StreamREader is inside the namespace System.IO.
  3. We are opening the ISolatedStorageFile for the SilverLight Application.
  4. We are checking, that if file name provided by user does not exist then displaying the message that file name does not exist.
  5. We are opening the file in Read Mode and reading the stream into a string.

 How to delete file?

private void btnDelete_Click(object sender, System.Windows.RoutedEventArgs e){
using (var store = IsolatedStorageFile.GetUserStoreForApplication()){
if (!(store.FileExists(txtFileName.Text))){
MessageBox.Show(“File does not exist “);
}
else{ store.DeleteFile(txtFileName.Text);
MessageBox.Show(“Deleted”);}
txtFileName.Text = “”;}}

 Explanation

  1. We are calling the DeleteFile method on instance of ISolatedStorageFile.

Complete code is as below

MainPage.xaml.cs

 

using System;using System.Collections.Generic;

using System.Linq;

using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.IO.IsolatedStorage;
namespace FileReadingandWritingwithIsolatedStorage
{
public partial class MainPage : UserControl{
public MainPage(){

InitializeComponent();
}
private void btnRead_Click(object sender, System.Windows.RoutedEventArgs e)
{
 

using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!(store.FileExists(txtFileName.Text))){
MessageBox.Show(“File does not exist “);
txtFileName.Text = “”;
}
else
{
using (StreamReader sr = new StreamReader(store.OpenFile(txtFileName.Text, FileMode.Open, FileAccess.ReadWrite)))
{
txtContent.Text = sr.ReadToEnd();
}}}}

private void btnWrite_Click(object sender, System.Windows.RoutedEventArgs e)
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!(store.FileExists(txtFileName.Text))){
MessageBox.Show(“File does not exist , we are creating one for you “);
IsolatedStorageFileStream file = store.CreateFile(txtFileName.Text);
file.Close();
}
using (StreamWriter sw = new StreamWriter(store.OpenFile(txtFileName.Text, FileMode.Open, FileAccess.Write)))
{
sw.WriteLine(txtContent.Text);
}
txtContent.Text = “”;

txtFileName.Text = “”;
MessageBox.Show(“File Writen”);
}}
private void btnDelete_Click(object sender, System.Windows.RoutedEventArgs e)
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!(store.FileExists(txtFileName.Text))){
MessageBox.Show(“File does not exist “);
}
else
{
store.DeleteFile(txtFileName.Text);
MessageBox.Show(“Deleted”);
}
txtFileName.Text = “”;
}}}}

Isolated Storage in Silver Light

Why Isolated Storage?

SilverLight applications are partially trusted application, which are running on a sandbox environment. So, SilverLight applications are not allowed to access the file system of the client, where it is running for the security reason. Because it is not safe to allow any SilverLight application to access client computer, this may harm many important system files. Because we know some SilverLight application might be potential malicious application. And we don’t want while browsing, any harmful SilverLight application to access our file system and harm them.But some time, SilverLight application needs some restricted access to client local file system for business requirement. Like Reading and Writing user specific file at client location or saving the personal information specific to user at client side etc. So, above purpose is achieved by SilverLight application using ISOLATED STORAGE.


Cookies and Isolated Storage 

Isolation

Isolated storage is composed of many different unique stores. Each of which can be thought of as its own virtual file system. This virtual file system is in isolation with the file system of operating system, such that malicious SilverLight application can not have access to the original file system.

Location of the Isolated Storage

Operating System

Location

Windows VISTA <SYSDRIVE>\Users\<user>\AppData\LocalLow\Microsoft\Silverlight\is
   
Windows XP <SYSDRIVE>\Document and Settings\<user>\Local Setting\Application data\Microsoft\Silver light\is
   

 SiliverLight application has access to two different stores.


SILVERLIGHT application has access of

  1. User + Application store
  2. User + Site store

Few Important points

  1. A SilverLight Application can access only its own application store. It cannot access store of other application.
  2. The Application Store is based on the, identity of the user and identity of the application.
  3. The identity of the application is full URL of the XAP file of the Silver light Application. For example www.c-sharpcorner.com\Application1.xap
  4. Application identity is case insensitive.


 Sample:
This sample will demonstrate how to use with Application level setting of IsolatedStorageSetting class.

  1. After entering User Name is textbox , when user will click Save Me. That user name will get added in the isolated file created for the application.
  2. On clicking on Reset Me button value saved against UserName key, will get deleted from the isolated file.
  3. At each time application will loaded, saved UserName will get display in the textbox

Step 1

Create a private global variable of the type IsolatedStorageSetting for the Application level.
private IsolatedStorageSettings app = IsolatedStorageSettings.ApplicationSettings;

Step 2

On the Save button click, we will be checking if checkbox is checked, we will check whether

  1. UserName key is existing in App or not. If not, we will add UserName key.
  2. We will set value for UserName key from the user name text box.
  3. App.add() is used to add new key in the application.
private void btnSave_Click(object sender, System.Windows.RoutedEventArgs e){

if (chkSave.IsChecked == true)
{
if (!(app.Contains(“UserName”)))
{
app.Add(“UserName”,“User Name has not Set “);
}
app[“UserName”] = txtUname.Text;
} }

 Step 3
On the Reset button, we are simple removing the key from the app setting.

private void btnReset_Click(object sender, System.Windows.RoutedEventArgs e)

{

app.Remove(“UserName”);

txtUname.Text = “”;}

 Step 4
On the Page Load, I am displaying the saved value for the key UserName from the isolated storage.

void MainPage_Loaded(object sender, RoutedEventArgs e){

if (app.Contains(“UserName”))
{
txtUname.Text = app[“UserName”].ToString();
}}

 So, the complete code is as below,
MainPage.Xaml

<UserControl x:Class=”IsolatedStorageSample1.MainPage”
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation

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

Width=”Auto” Height=”Auto”>

<Grid x:Name=”LayoutRoot” Background=”#FF7F4343″ Width=”400″ Height=”400″>

<Grid.ColumnDefinitions>    
 <ColumnDefinition Width=”0.385*”/>
<ColumnDefinition Width=”0.615*”/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>

<RowDefinition Height=”0.25*”/>
<RowDefinition Height=”0.157*”/>
<RowDefinition Height=”0.593*”/>
 </Grid.RowDefinitions>
<TextBox x:Name=”txtUname” Margin=”10,10,10,10″ Grid.Column=”1″ Text=”” TextWrapping=”Wrap”Background=”#FF230303″ BorderThickness=”2,2,2,2″ FontSize=”16″ FontWeight=”Bold” Foreground=”#FFF81616″/>
 <TextBlock Margin=”8,8,8,8″ Text=”UserName” TextWrapping=”Wrap” FontSize=”12″ FontWeight=”Bold”Foreground=”#FF342A2A” FontFamily=”Arial Rounded MT Bold”/>
<CheckBox x:Name=”chkSave” Margin=”10,10,10,10″ Grid.Row=”1″ Content=”Save User Name” IsChecked=”True” FontWeight=”Bold” FontSize=”12″
BorderThickness=”2,2,2,2″ Foreground=”#FF150808″ FontFamily=”Arial Rounded MT Bold”/>
<Grid Margin=”8,10,12,8″ Grid.Column=”1″ Grid.Row=”1″>

 <Grid.ColumnDefinitions>

<ColumnDefinition Width=”0.385*”/>
<ColumnDefinition Width=”0.615*”/>
 </Grid.ColumnDefinitions>

<Button x:Name=”btnSave” Margin=”2,2,2,2″ Content=”Save Me” Grid.Row=”0″ Grid.Column=”0″ Click=”btnSave_Click”/>

<Button x:Name=”btnReset” Margin=”2,2,2,2″ Content=”Reset Me “ Grid.Row=”0″ Grid.Column=”1″ Click=”btnReset_Click”/>
 </Grid>
</Grid>
</UserControl>

 MainPage.Xaml.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using System.IO.IsolatedStorage;

 namespace IsolatedStorageSample1{
public partial class MainPage : UserControl{
private IsolatedStorageSettings app = IsolatedStorageSettings.ApplicationSettings;
public MainPage(){

InitializeComponent();
Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e){
if (app.Contains(“UserName”)){
txtUname.Text = app[“UserName”].ToString();
}}
private void btnSave_Click(object sender, System.Windows.RoutedEventArgs e)

{
if (chkSave.IsChecked == true){
if (!(app.Contains(“UserName”)))
{
app.Add(“UserName”,“User Name has not Set “);
}
app[“UserName”] = txtUname.Text;}}
private void btnReset_Click(object sender, System.Windows.RoutedEventArgs e){
app.Remove(“UserName”);

txtUname.Text = “”;}}}

 Output:


After clicking Refresh again we will get the same output. If we click Reset and then press F5, we will get output as below.


Quota in Isolated Storage

  1. A quota is limit on the amount of isolated storage space that can be used by the application.
  2. A Quota Group is group of isolated Store that shares the same quota.
  3. In Silver Light, stores are grouped by the site. So all the application with same site identity shares the same quota.
  4. Isolated Storage could have zero or more quota groups.

  1. An Application can request more space for the quota group

      

  2.    Sample on how to modify the quota?
    I have added the below code on the click event of Save Button. So now the save Button click event is as below. I have modified the above code sample. See the code in Red rectangle.
private void btnSave_Click(object sender, System.Windows.RoutedEventArgs e){

if (chkSave.IsChecked == true){
if (!(app.Contains(“UserName”)))
{
app.Add(“UserName”,“User Name has not Set “);
}
app[“UserName”] = txtUname.Text;
}
using (var store = IsolatedStorageFile.GetUserStoreForApplication()){
int spaceneed = 1024 * 1024 * 5;
if (store.AvailableFreeSpace < spaceneed){
if (store.IncreaseQuotaTo(store.Quota + spaceneed)){
MessageBox.Show(“User Has approved the quota Increase”);
MessageBox.Show(store.AvailableFreeSpace.ToString());
}
else{
MessageBox.Show(“User Has Not Approved the quota Increase “);
MessageBox.Show(store.AvailableFreeSpace.ToString());
}} } }

 Output
User is getting prompt for Approval.


 When User is not approving means selecting “No”. The default size is getting displayed in message box.


When User is approving means selecting “Yes”. The increased size is getting displayed in message box.

Refresh a DataGrid dynamically in SilverLight

Objective

Core Objective of this article is to give step by step explnation of , How to update or refresh a DataGrid dynamically in SilverLight ?

  1. List which is to be bind must be ObservableCollection
  2. Item of list of business class must implement INotifyPropertyChanged interface.

This article is explaning how DataGrid would get refresh dynamically whenever value in list would be changed.

Step 1Create a SilverLight Application.Add one more new class. Give it any name. Name of that is EventBase. Purpose of this class is to act as a base class for which will implement INotifyPropertyChange

  1. Add namepsace  using System.ComponentModel;
  2. Implement interface INotifyPropertyChanged
  3. Make class as abstarct class.
  4. Declare an public event of type PropertyChangedEventHandler

    The entire code will look like

EventBase.cs

using System.ComponentModel;

namespace AutometicRefreshTesting{
public abstract class EventBase : INotifyPropertyChanged{
public event PropertyChangedEventHandler PropertyChanged;
protected void PropertyChangedHandler(string propertyName)
{

var handler = PropertyChanged;
if (handler != null)
{

handler(this, new
PropertyChangedEventArgs(propertyName));
}}}}

Step 3

Add a new class in Silver Light application. Name it as Player.cs. This is Business class. This class will extend EventBase class. In property, we are calling PropertyChangedHandler(“”) method of EventBase class to create a notify whenever value in property being changed.

set{

playerId = value;

PropertyChangedHandler(“PlayerID”);
}

 Player.cs

namespace AutometicRefreshTesting{

public class Player : EventBase {
private int playerId;

public int PlayerID
{get { return playerId;}

set{ playerId = value;

propertyChangedHandler(“PlayerID”);}}
private String playerName;
public String PlayerName
{ get {return playerName;}
set { playerName = value;

PropertyChangedHandler(“playerName”);}}

private String countryName;
public String CountryName
{ get{ return countryName;}
set{countryName = value;

PropertyChangedHandler(“CountryName”);
} } }}

 Step 4
Add a Button and DataGrid on XAML of page.

  1. DataGrid could be dragged and drop from ToolBox for SilverLight.
  2. Here Grid is divided into two columns. One column is containing Button and other is containing DataGrid.

MainPage.Xaml

<UserControl xmlns:data=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data”
x:Class=”AutometicRefreshTesting.MainPage”

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

Width=”400″ Height=”300″>

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

<Grid.ColumnDefinitions>

<ColumnDefinition Width=”Auto”/>

<ColumnDefinition Width=”Auto” MinWidth=”337″/>
</Grid.ColumnDefinitions>

<Grid.RowDefinitions>
</Grid.RowDefinitions>

<Button x:Name=”btnAdd” Content=”Add Player to Static List” Width=”150″ Height=”50″ Grid.Row=”0″ Grid.Column=”0″ Click=”btnAdd_Click” />

<data:DataGrid x:Name=”dataList”Grid.Row=”0″ Grid.Column=”1″>
</data:DataGrid>
</Grid>
</UserControl>

 Step 5
For Dynamic updating or refresh of Data Grid, the List which is to be bind with Data Grid must be a ObservableCollection ist. What I am doing here is that adds record on button click event to the list and dynamically refresh the DataGrid.


MainPage.Xaml.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;

using System.Windows.Shapes;

using System.Collections.ObjectModel;
namespace AutometicRefreshTesting{
public prtial cass MainPage : UserControl{
ObservableCollection<Player> playerList;
static int i = 2;
public MainPage(){
InitializeComponent();
playerList = new ObservableCollection<Player>();
playerList.Add(new Player(){PlayerID=1,PlayerName=“MS Dhoni”,CountryName=“India”});
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
dataList.ItemsSource = playerList;}

privatevoid btnAdd_Click(object sender, RoutedEventArgs e){
Player obj = new Player() { PlayerID = i, PlayerName = “Sachin Tendulkar “, CountryName = “India” };

playerList.Add(obj);
dataList.ItemsSource = playerList;
i= i+1 ;
}}}

Conclusion
Here I mainly showed how to automatically update the DataGrid when Item source is changing. Please download the zip file and go through the source code for better understanding.

Navigation in Silver Light

Objective

This article will show, How to navigate between two SilverLight pages in silverLight2.0. This article is giving step by step illustration on how to navigate and pass values between two SilverLight pages. In this SilverLight application user will input her name and two numbers in one Silverlight page and user will get greeting message and summation of input number in other SilverLight page.

 Step 1
Create a Silver Light application.

  1. Open visual studio
  2. Select File->New ->Project -> Web
  3. Navigate to Silver Light tab.
  4. Select Silver Light application.
  5. Give any meaningful name. I am giving name here, SilverLightNavigation.
  6. lect hosting the application into web project.

 Step 2

  1. Delete MainPage.Xmal from Silver Light project.
  2. Add two new user controls to Silver Light project. To do so Right click on Silver Light project and add new Item. Navigate to Silver Light tab. Then select Silverlight user control. Give name of the user controls as Page1 and Page2.    

 Step 3
Open App.Xaml.cs file.

  1. Declare a container element.

    Grid navigationUI = new Grid(); 

  2. Add the page, which is to be navigating as the child of the container we just created.
    this.RootVisual = navigationUI;
    navigationUI.Children.Add(new Page1());
  3. Now we will take three private variables inside App.Xaml.cs. one for username as string and two for two inegers to be added. 
private string name;
private int number1;

private int number2;

public string Name
{ get { return name;}set{name = value;}}
public int Number1 { get{ return number1;}set{number1 = value;}}
public int Number2{get{return number2 ;}set{number2 = value;}}
  1. Now we will add a static method, which will navigate the pages.

public static void NavigateToPage(UserControl page)
{

App application = (App)Application.Current;

application.navigationUI.Children.Clear();

application.navigationUI.Children.Add(page);}

So, the entire App.Xaml.cs file will look like below. Codes in red rectangle are added by us.

App.Xaml.cs

namespace SilverLightNavigation{

public partial class App : Applicatio{

private string name;
private int number1;
private int number2;
public string Name{ get { return name; }set{name = value;}}
public int Number1 {get return number1;}set{number1 = value;}}
public int Number2
{get{return number2 ;}set{number2 = value;}}
Grid navigationUI = newGrid();
public App()
{
this.Startup += this.Application_Startup;
this.Exit += this.Application_Exit;

this.UnhandledException += this.Application_UnhandledException;

IitializeComponent();}
private void Application_Startup(object sender, StartupEventArgs e)
{
this.RootVisual = navigationUI;

navigationUI.Children.Add(newPage1());}


private void Application_Exit(object sender, EventArgs e){}
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (!System.Diagnostics.Debugger.IsAttached)
{
e.Handled = true;
Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });}}

privatevoid ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e){

try
{
string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
errorMsg = errorMsg.Replace(‘”‘, ‘\”).Replace(“\r\n”, @”\n”);
System.Windows.Browser.HtmlPage.Window.Eval(“throw new Error(\”Unhandled Error in Silverlight Application “+ errorMsg + “\”);”);
}
catch (Exception){}
}
public static void NavigateToPage(UserControl page)
{
App application = (App) Application.Current;

application.navigationUI.Children.Clear();application.navigationUI.Children.Add(page);

}}}

Step 4

Now create or customize the XAML of Page1 for user interface. It contains three text boxes to get user input. And one Button to navigate to other page.

Page1.Xaml

<UserControl x:Class=”SilverLightNavigation.Page1″
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation

xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
Width=”auto” Height=”auto”>

<Grid x:Name=”LayoutRoot” Background=”White” Height=”600″ Width=”600″>

<Grid.ColumnDefinitions>

<ColumnDefinition Width=”*” />

<ColumnDefinition Width=”*” />

</Grid.ColumnDefinitions>

Grid.RowDefinitions>
<RowDefinition Height=”*” />

<RowDefinition Height=”*” />

<RowDefinition Height=”*” />
<RowDefinition Height=”*” />

</Grid.RowDefinitions>

<TextBlock x:Name=”lblUname” Grid.Column=”0″ Grid.Row=”0″ Text=”UserName” />

<TextBox x:Name=”txtUname” Grid.Column=”1″ Grid.Row=”0″ Height=”50″ Width=”150″ />

<TextBlock x:Name=”lblNum1″ Grid.Column=”0″ Grid.Row=”1″ Text=”Number1″ />

<TextBox x:Name=”txtNum1″ Grid.Column=”1″ Grid.Row=”1″ Height=”50″ Width=”150″ />

<TextBlock x:Name=”lblNum2″ Grid.Column=”0″ Grid.Row=”2″ Text=”Number2″ />
<TextBox x:Name=”txtNum2″ Grid.Column=”1″ Grid.Row=”2″ Height=”50″ Width=”150″ />
<Button x:Name=”btnNavigate” Content=”Click me For Navigation and Result” Height=”100″ Width=”300″ Grid.Column=”0″ Grid.Row=”3″ Click=”btnNavigate_Click/>
</Grid>
</UserControl>

 Step 5:

On the click event of button

Create instance of current applicationCall the static method to navigate to other page.
Page1.Xaml.cs

 

 namespace SilverLightNavigation
{
public partial class Page1 : UserControl
{
public Page1()
{
InitializeComponent();
}
private void btnNavigate_Click(object sender, RoutedEventArgs e)
{

App application = (App)Application.Current;

application.Name = txtUname.Text;
application.Number1 = Convert.ToInt32(txtNum1.Text);

application.Number2 = Convert.ToInt32(txtNum2.Text);


App.NavigateToPage(newPage2());
}}}

 Step 6:
Now create or customize the XAML of Page2 to display the result and User name. it contains two labels. One to display user name, and other two display sum of two numbers. This page also contains one Button to navigate to previous page.
Page2.Xaml

<UserControl x:Class=”SilverLightNavigation.Page2″
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation

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

Width=”auto” Height=”auto”>

<Grid x:Name=”LayoutRoot” Background=”White” Height=”500″ Width=”600″>

<Grid.RowDefinitions>

<RowDefinition Height=”*” />

<RowDefinition Height=”*” />

<RowDefinition Height=”*” />

</Grid.RowDefinitions>

<TextBlock x:Name=”txtUserDisplay” Grid.Row=”0″ Text=”Welcome to Navigated Page ” />
<TextBlock x:Name=”txtResult” Grid.Row=”1″Text=”Sumation of two Numbers = ” />

<Button x:Name=”btnNavigateback” Grid.Row=”2″ Height=”100″ Width=”200″ Content=”Navigate to back Page” Click=”btnNavigateback_Click” />
</Grid>
</UserControl>

Step 7

Add below code in code behind to display user name and summation of two numbers. Also add below code to navigate to previous page.

Page2.Xaml.cs

 

 namespace SilverLightNavigation
{
public partial class age2 : UserControl
{
public Page2(){
InitializeComponent();
App application = (App)Application.Current;
txtUserDisplay.Text = txtUserDisplay.Text + application.Name;
int res = application.Number1 + application.Number2 ;
txtResult.Text = txtResult.Text + res.ToString();
}
private  vid btnNavigateback_Click(object sender, RoutedEventArgs e)
{
App.NavigateToPage(newPage1());
}}}

Press F5 to run with debugging and test your application. In this article, we saw how to navigate between two Silver Light pages and pass value in between them. Happy coding

Silver Light with ASP.Net MVC Framework

Objective

In this tutorial, We will fetch data from SQL Server database using LINQ and display that data in Silver Light, while we are following ASP.Net MVC Framework


Step 1
Create a Silver Light application.
File -> New -> Project -> Silver Light


Step 2
To hosting SILVERLIGHT application there are three options available for hosting a Silver Light application. Select ASP.Net MVC Web project. Then after, Select option NO for creating UNIT Test Project.
Step 3

Right click on Controller. Click on Add-> New Item and select add LINQ to SQL classes. Give a name.
Step 4

Here, I have already created a TEST data base in my database. I am going to display data from this database.

  1. Open Server Explorer
  2. Right click on Data Connection
  3. Click Add New Data Connection.

Now give a Server name and select database to connect
Expand test.dbo. Here there are 2 tables in Test database. One is Test_Details and other is testsample. In this tutorial, I am going to display data from Test_Detatils table. So select this table from Server explorer and drag it on Test.dbml page. Now if you click on Test.Dbml.CS file. You will find code has been created for you.Up to this step, Linq class has been created.

Step 5

We will add here one more action called List inside Home Controller. Purpose of this action is to fetch out all records of Test_Details table and return List of records as JSON. Add following code in Home Controller class. Don’t forget to include at the top of HomeController.cs .

using SilverLightMvcTest.Web.Models;public ActionResult List()

{

TestDataContext _obj = new TestDataContext();

var _res = from r in _obj.Test_Details

select r;

return Json(_res);

 }

The above action List is returning JSON of all the records fetch from Test_Dtails table of Test Database.So now the complete code of HomeController.cs will look like,
HomeController.cs

using System;using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using SilverLightMvcTest.Web.Models;

 namespace SilverLightMvcTest.Web.Controllers

{

[HandleError]

public class HomeController : Controller
{

public ActionResult Index()

{

ViewData[“Message”] = “Welcome to ASP.NET MVC!”; return View();

}

public ActionResult About()

{

return View();

}

 public ActionResult List()

{

TestDataContext _obj = new TestDataContext();

var _res = from r in _obj.Test_Details

select r;

return Json(_res);

}

}

}

 Step 6
Now click on View -> Home -> Right Click -> Add -> View.Give name of the View exactly of action name. Here action name is List so name of view will be List. Leave other things as default and click on Add. It will create a List.aspx page.


List.aspx will have following code. 

<%@ Page
Title=”” Language=”C#” MasterPageFile=”~/Views/Shared/Site.Master” Inherits=”System.Web.Mvc.ViewPage” %>
<asp:Content ID=”Content1″ ContentPlaceHolderID=”head” runat=”server”>

<title>List</title>

</asp:Content>

<asp:Content ID=”Content2″ ContentPlaceHolderID=”MainContent” runat=”server”>

<h2>List</h2>

</asp:Content>

 Remove
<h2>List</h2>
And add below code

<p><object data=””data:application/x-silverlight-2type=”application/x-silverlight-2″
width=”300px” height=”300px”>
<param name=”source” value=”/ClientBin/SilverLightMvcTest.xap/>
<param name=”minRuntimeVersion” value=”2.0.31005.0″
/>
<param name=”windowless” value=”true”
/>
<param name=”Background” value=”#00FFFFFF”
/>
</object>
</p>

 Here at value property of source, name is SilverLightMvcTest.xap . Here make sure you are giving the name, which name you gave to your SilverLight Project at Step 1

So now complete code for List.aspx would be

List.aspx

<%@ Page
Title=”” Language=”C#” MasterPageFile=”~/Views/Shared/Site.Master” Inherits=”System.Web.Mvc.ViewPage” %>
 <asp:Content ID=”Content1″ ContentPlaceHolderID=”head” runat=”server”>

<title>List</title>

</asp:Content

<asp:Content ID=”Content2″ ContentPlaceHolderID=”MainContent” runat=”server”>

 <p>

<object data=””data:application/x-silverlight-2type=”application/x-silverlight-2″ width=”300px” height=”300px”>

<param name=”source” value=”/ClientBin/SilverLightMvcTest.xap” />

<param name=”minRuntimeVersion” value=”2.0.31005.0″ />

<param name=”windowless” value=”true” />

<param name=”Background” value=”#00FFFFFF” />

</object>

</p>

 </asp:Content>

 Step 8

Page.Xaml.cs

<UserControl
x:Class=”SilverLightMvcTest.Page”xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;

xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;

xmlns:data=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data”

Width=”400″ Height=”300″>

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

<Grid.RowDefinitions>

<RowDefinition Height=”Auto” />

<RowDefinition Height=”Auto” />

</Grid.RowDefinitions>    

<Grid.ColumnDefinitions>

<ColumnDefinition Width=”Auto” />

 

</Grid.ColumnDefinitions>

<Button x:Name=”b1″ Height=”100″ Width=”100″ Click=”b1_Click” Grid.Row=”0″ Grid.Column=”1″/>
<data:DataGrid x:Name=”MyGrid” Grid.Row=”1″ Grid.Column=”1″>
</data:DataGrid>
</Grid> </UserControl>

<ColumnDefinition Width=”Auto” />

 Step 9
Right click on SilverLight Project and add new class . Give it name Test_Details.Add following code in Test_Details.cs

Test_Details.cs

namespace SilverLightMvcTest{

public class Test_Details
{

public string testId { get; set; }

public string testName { set; get; }

public int testMaxMarks {  set; get; } } }

 Make sure here property name and return type is exactly same of the column name and types in table of database.

Step 10

  1. Run your application, by clicking F5.
  2. Below screen will come
  3. Click on address bar and type

     http://localhost:2675/home/list
    Copy this URL.

Step 11

  1. Add a reference to System.RunTime.Serilization and System.ServiceModel.Web to SilverLight Project.
  2. Include namespace

    using System.Runtime.Serialization.Json to Page.Xaml.Cs

     Page.Xaml.CS
     

using System;using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using System.Runtime.Serialization.Json;

namespace SilverLightMvcTest

{

public partial class Page : UserControl
{

public Page()

{

InitializeComponent();

}

 private void b1_Click(object sender, RoutedEventArgs e)

{

WebClient _client = new WebClient();

_client.OpenReadCompleted += newOpenReadCompletedEventHandler(_client_OpenReadCompleted);

client.OpenReadAsync(newUri(http://localhost:2675/home/list&#8221;)); }

 void _client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)

{

DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(List<Test_Details>));

 IList<Test_Details> res = (List<Test_Details>)(json.ReadObject(e.Result));

 MyGrid.ItemsSource = res;

} } }

Run the application.

Run Time Binding in SilverLight

Objective

This tutorial will explain

Introduction of Run Time Binding in SilverLIght
Example to achieve run time binding.

Explanation
We are having an IPL class. A list objlist is there which is containing numbers of IPL objects. Our example will fetch data from that list and display in silver light control on click event of button. For this purpose, we are using RUN TIME BINDING.
Run Time Binding in SilverLight application

Binding a Silver Light application entirely through .Net code is Run Time Binding.It is very useful when Source and Property are not known at the design time.Binding could be created using System.Windows.Data namespace and using instance of Binding class.It allows changing binding at run time.Run Time Decision of setting the Property. So in below situation we need to use Run Time Binding.


 Binding class

This class could be created using XAML markup extension also.It is inside namespace System.Window.Data.It contains all the property which was supported in XAML markup code. Properties are shown in below figure.

Source -> It points to the source object

Path -> It points to the source object property


Constructor of Binding class is overloaded with two parameters. We could pass either Zero argument or a string Path value. Both are shown in below figures


 SetBinding method
It is use to link the binding instance with their corresponding Targets.It is method of FrameWorkElement base class.
It takes two parameters as input.Dependency Property and Binding Instance

The way to find out, which object supports binding. Just we need to check that object having SetBinding method or not.

 Steps to create Run Time Binding

Step 1

Create new instance of Binding object for each target and source pair. Code for that is given below.

Step 2
Set the source property. Source property will get set to the instance of the business class.( In our case it is IPL.)
 

IPL _obj;.

_obj= new IPL();

pNameBinding.Source = _obj;

tNameBinding.Source = _obj;

cNameBinding.Source = _obj;iscaptionBinding.Source = _obj

 Step 3
Now to Link Binding instance with their corresponding target.

pName.SetBinding(TextBox.TextProperty, pNameBinding);

tName.SetBinding(TextBox.TextProperty, tNameBinding);cName.SetBinding(TextBox.TextProperty, cNameBinding);

isCaption.SetBinding(CheckBox.IsCheckedProperty, iscaptionBinding);

 Example and code to achieve above said output
 

Step 1
Create a Silver Light application.Replace Page.Xaml.Cs file with below code.
Page.Xaml.cs

<UserControl x:Class=”SilverlightBindingTesting.MainPage”
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation

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

Width=”400″ Height=”300″>

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

<Grid.RowDefinitions>

<RowDefinition />

</Grid.RowDefinitions>

<Grid.ColumnDefinitions>
<ColumnDefinition />
</Grid.ColumnDefinitions>

<Rectangle Fill=”#FFDEE6FB” Grid.Column=”0″ Grid.Row=”0″ RadiusX=”20″ RadiusY=”20″ Opacity=”0.8″ StrokeThickness=”0″ />

<Grid Grid.Column=”0″ Grid.Row=”0″ Margin=”10,10,10,10″>

<Grid.ColumnDefinitions>

<ColumnDefinition Width=”80″ />

<ColumnDefinition Width=”260″ />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height=”*” />
<RowDefinition Height=”*” />

<RowDefinition Height=”*” />

<RowDefinition Height=”*” />

<RowDefinition Height=”*” />

</Grid.RowDefinitions>

<TextBlock Text=”NAME” Margin=”10,5,10,5″ Grid.Row=”0″ Grid.Column=”0″ FontSize=”15″ Foreground=”BlueViolet” />

<TextBlock Text=”TEAM” Margin=”10,5,10,5″ Grid.Row=”1″ Grid.Column=”0″ FontSize=”15″ Foreground=”BlueViolet” />

<TextBlock Text=”COUNTRY” Margin=”10,5,10,5″ Grid.Row=”2″ Grid.Column=”0″ FontSize=”12″ Foreground=”BlueViolet” />

<TextBlock Text=”CAPTION” Margin=”10,5,10,5″ Grid.Row=”3″ Grid.Column=”0″ FontSize=”12″ Foreground=”BlueViolet” />

<TextBox x:Name=”pName” Margin=”10,5,10,5″ Grid.Row=”0″ Grid.Column=”1″ FontSize=”9″ Foreground=”Black” />

<TextBox x:Name=”tName” Margin=”10,5,10,5″ Grid.Row=”1″ Grid.Column=”1″ FontSize=”9″ Foreground=”Black” />

<TextBox x:Name=”cName” Margin=”10,5,10,5″ Grid.Row=”2″ Grid.Column=”1″ FontSize=”9″ Foreground=”Black” />

<CheckBox x:Name=”isCaption” Margin=”10,5,10,5″ Grid.Row=”3″ Grid.Column=”1″ />
<Button x:Name=”bindData” Margin=”10,5,10,5″ Grid.Row=”4″ Grid.Column=”1″ Content=”PLAYERS” FontSize=”10″ Foreground=”Red” Click=”bindData_Click” />
</Grid>
</Grid></UserControl>

 Step 2
Right click on project and add a new class. Name this class as IPL
IPL.cs

namespace SilverlightBindingTesting{public class IPL{
public string  Player_Name { get; set; }
public string Team_Name { get; set; }

public string Country_Name { get; set; }

public bool IsCaption { get; set; }
}}

 Step 3
Open Page.Xaml.Cs file and replace with below code. This code is containing simple logic to bind data.
Page.Xaml.cs

using System;using System.Collections.Generic;using System.Linq;

using System.Net;

using System.Windows;using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using System.Windows.Data; 

namespace SilverlightBindingTesting{

public partial class MainPage : UserControl{
static int i;

IPL _obj;

List<IPL> objlist = new List<IPL>();

public MainPage()
{

InitializeComponent();
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
_obj= new IPL();

_obj.Country_Name=“India”;

_obj.IsCaption=true;

_obj.Player_Name=“Sachin Tendulakr”;_obj.Team_Name=“Mumbai Indian “; 

objlist.Add(_obj); 

_obj = new IPL(); 

_obj.Country_Name = “England”;

_obj.IsCaption = true;

_obj.Player_Name = “Kelivin Piterson”;

_obj.Team_Name = “Royal Challenger Bangalore”; 

objlist.Add(_obj); 

_obj = new IPL();

_obj.Country_Name = “India”;

_obj.IsCaption = false;

_obj.Player_Name = “Herchle Gibbs”;

_obj.Team_Name = “Deccan Charger Hyderabad”; 

objlist.Add(_obj);}

private void bindData_Click(object sender, RoutedEventArgs e)
{
if (i >= objlist.Count){
i = 0;}
functionDisplay(i);
i++;}
void functionDisplay(int i){
var pNameBinding = new Binding(“Player_Name”);
var tNameBinding = new Binding(“Team_Name”);

var cNameBinding = new Binding(“Country_Name”);

var iscaptionBinding = new Binding(“IsCaption”);

pNameBinding.Source = objlist[i];

tNameBinding.Source = objlist[i];cNameBinding.Source = objlist[i];

iscaptionBinding.Source = objlist[i];

pName.SetBinding(TextBox.TextProperty, pNameBinding);

tName.SetBinding(TextBox.TextProperty, tNameBinding);

cName.SetBinding(TextBox.TextProperty, cNameBinding);

isCaption.SetBinding(CheckBox.IsCheckedProperty, iscaptionBinding);} }}

 Step 4
Press F5 and run the application. You will get output
Happy Coding .

Custom Panel in Silver Light

Objective

 Now it is time to get rid of default layouts of SilverLight. In this article, we will learn how to create a very basic custom layout and how to use that in SilverLight application.
Step 1

Create a new Silver Light application.

Step 2

Add a class in SilverLight application. Give any name for this class. My name is here MyPanel.

Step 3

Extend Panel class in MyPanel class.

namespace MargiesTravel.Controls{

public class MyPanel :Panel
{}}
Step 4

Now task is to find desired size of each child. To find desire size of each children, our custom panel will have to call Measure() function on each child.

Measure() function could be called by overriding MeasureOverride function of Panel class. This could be done as

protected override Size MeasureOverride(Size availableSize){

foreach (UIElement child in Children)
{
child.Measure(availableSize);
}
return base.MeasureOverride(availableSize);
}
aviliableSize is the variable which shows size available to the custom Panel. If child desired size is 300 pixels and aviliableSize is 200 pixels then, child size will be clipped.


Step 5
After reading the desire size of each child, now time to arrange them in custom panel. For this purpose MyPanel class will override ArrangeOverride method of Panel class.
protected override  Size ArrangeOverride(Size finalSize){}

 Now, we will implement ArrangeOverride method to place the child into MyPanel.

protected override Size ArrangeOverride(Size finalSize){

//return base.ArrangeOverride(finalSize);
double currentLeft = 0;

double currentTop = 0;

double currentRowHeight = 0;

foreach (UIElement child in Children)
{
if ((currentLeft + child.DesiredSize.Width) > finalSize.Width)
{

currentLeft = 0;

currentTop += currentRowHeight;
currentRowHeight = 0;
}
child.Arrange(new Rect(currentLeft, currentTop, child.DesiredSize.Width, child.DesiredSize.Height));

currentLeft += child.DesiredSize.Width;

currentRowHeight = Math.Max(currentRowHeight, child.DesiredSize.Height);
}
return finalSize;
}


So, the entire MyPanel class will look like

MyPanel.cs
 using System;

using System.Net;

using System.Windows;using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Ink;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes; 

namespace MargiesTravel.Controls{

publicclass MyPanel :Panel{

protected override Size MeasureOverride(Size availableSize){
foreach (UIElement child in Children)
{

child.Measure(availableSize);
}
return base.MeasureOverride(availableSize);
}
protected override Size ArrangeOverride(Size finalSize)
{
double currentLeft = 0;
double currentTop = 0;

double currentRowHeight = 0;

foreach (UIElement child in Children)
{
if ((currentLeft + child.DesiredSize.Width) > finalSize.Width)
{

currentLeft = 0;

currentTop += currentRowHeight;

currentRowHeight = 0;}
child.Arrange(new Rect(currentLeft, currentTop, child.DesiredSize.Width, child.DesiredSize.Height));

currentLeft += child.DesiredSize.Width;

currentRowHeight = Math.Max(currentRowHeight, child.DesiredSize.Height);}
return finalSize;}}}
Up to this step, custom panel called MyPanel has been created.

Step 6

Go to MainPage.xaml of your SilverLight application.

  1. Inherit the namespace of the class MyPanel. In my case namespace name is MargiesTravel.Controls

xmlns:cl=”clr-namespace:MargiesTravel.Controls”

  1. Put our custom panel inside the default Grid panel.

<Grid x:Name=”LayoutRoot” Background=””>

<cl:MyPanel>

</cl:MyPanel>

  1. Put some control inside the custom panel. After putting controls Xaml code will look like.

MainPage.xaml

<UserControl x:Class=”MargiesTravel.Controls.MainPage”
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation

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

xmlns:cl=”clr-namespace:MargiesTravel.Controls”

Width=”800″ Height=”800″>

<Grid x:Name=”LayoutRoot” Background=”Blue”>

<cl:MyPanel>

<Button Content=”Child 1 for Custom panel “ Height=”200″ Width=”50″/>

<TextBlock
Text=”Child 2 for Custom Panel “ Width=”150″ Height=” 30″ />

<TextBlock
Text=”Child 3 for Custom Panel “ Width=”200″ Height=”130″ />

<Button Content=”Child 4 for Custom panel “ Height=”300″ Width=”100″/>

<TextBlock Text=”Child 5 for Custom Panel “ Width=”200″ Height=”50″ />

<Slider Width=”300″ Value=”10″ Height=”50″ />

<TextBox Text=” Child 6 for Custom Panel” Width=”200″ Height=”30″ />

<TextBlock Text=” Child 7 for Custom Panel”/>
<CheckBox Content=”Child 8 for Custom Panel” Width=”140″ />

<Slider Width=”300″ Value=”10″ Height=”50″ />

</cl:MyPanel>

</Grid>
</UserControl>

 Run the SilverLight Application.


 Conclusion
This article explained how to create a custom layout for SilverLight 2 application.
Happy Coding

Dependency Property

WPF introduces a new type of property called Dependency Property.

  1. This Property is backed by WPF property system.
  2. It is used for animation; enable styling, automatic data binding and more.
  3. It depends upon multiple providers for determining its value at any point of time.
  4. The biggest feature of Dependency Property is it’s built in ability to provide CHANGE NOTIFICATION.
  5. Main motive behind adding Dependency Property is to enable rich functionality directly from declarative markup language.
  6. The purpose of Dependency Property is to find value of property based on the value of other inputs.

    The other input might be

  • Style Themes
  • User Preferences
  • Just in time property determination
  • Animation etc. 

Example

 There are 96 public properties of Button. Properties can be easily set in XAML without any procedural code. But without extra plumbing of Dependency Property, it would be hard for the simple action of setting properties to get the desired result without writing extra code.
The purpose of dependency properties is to provide a way to compute the value of a property based on the value of other inputs.

Backing Object Property with Dependency Property , allowing to have support for Data Binding, Animation, Default Value, Styling etc.

 Dependency Property supports Multiple Providers. In order to get final value of Dependency Property, these five steps have been run by WPF.

Step 1: Determine Base Value

The following provider set the base value for Dependency Property. They are here listed in order of their precedence (Highest to Lowest).

  1. Local Value
  2. Style Triggers
  3. Template Triggers
  4. Style setters
  5. Theme Style Triggers
  6. Theme Style Setters
  7. Property Value Inheritance
  8. Default value.

Step 2: Evaluate

If the value from Step1 is an expression, then it is finally getting evaluated here. WPF converts an expression into a concrete value.

Step 3: Apply Animation

If any animations are running they can either replace or alter the value of Dependency Property.

Step 4: Coerce

WPF takes final Property value and pass it to CorecevalueCallBack delegate. This is to check, whether any custom logic is running to set the value of Dependency Property. The callback is responsible for returning new value based on custom logic.

Step 5: Validate

Now final value is passed to ValidateValueCallBack delegate to check value is Valid or not.

Example of Dependency Property

Let, there is a requirement to

  1. Change Text color of Button with Mouse Hover.
  2. When Mouse Enters, text color should be change to BLUE
  3. When Mouse Leaves, text color changed back to BLACK.

     

    So without special feature CHANGE NOTIFICATION of Dependency Property

Step 1:


Create XAML tag for Button with two events , like below

<Window x:Class=”WpfApplication2.Window1″
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation

xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
Title=”Window1″ Loaded=”Window_Loaded”
Height=”300″ Width=”300″>

<Grid>

<Button MouseEnter=”Button_MouseEnter” MouseLeave=”Button_MouseLeave”
Height=”100″ Width=”100″> Testing Button </Button>

</Grid>
</Window> 

Here Button_MouseEnter and Button_MouseLeave is events.

 Step 2:

Now there is need to write code at back end to handles these events. Code will look like as follows

 private void Button_MouseEnter(object sender, MouseEventArgs e)
{
Button b = sender as Button;
if (b != null)
{
b.Foreground = Brushes.Blue;
}
}
private void Button_MouseLeave(object sender, MouseEventArgs e)
{
Button b = sender as Button;
if (b != null)
{
b.Background = Brushes.Black;
}
}
Now to achieve above task, XAML can be easily used with Dependency Property.

<Window x:Class=”WpfApplication2.Window1″
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation

xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
Title=”Window1″ Loaded=”Window_Loaded”
Height=”300″ Width=”300″>

<Grid>
<Button Height=”100″ MinWidth=”75″ Margin=”10″>

<Button.Style>

<Style TargetType=”{x:Type Button}”>

<Style.Triggers>

<Trigger Property=”IsMouseOver” Value=”True”>

<Setter Property=”Foreground” Value=”Blue”/>

</Trigger>

</Style.Triggers>

</Style>

</Button.Style>
OK
</Button>
</Grid>
</Window>
Happy Coding

Working with Radio Button control and Image in Silver Light 3.0

Objective

In this article, I will explain couple of things step by step

  1. How to work with Radio Button control of Silver Light 3.0
  2. How to Rotate Image in Silver Light

Expected Output


On selecting Radio Button Image will rotate in some angle.


 Procedure
Create a Silver Light application by File -> New -> Project -> SilverLight then selecting Silver Light Application project template. Host the SilverLightApplication1 in Web Application
Design the Silver Light page. Add Radio Buttons like below

MainPage.Xaml

<UserControl xmlns:data=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data”
x:Class=”SilverlightApplication1.MainPage”


xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;


xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;


xmlns:d=”http://schemas.microsoft.com/expression/blend/2008&#8243; xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006&#8243;


mc:Ignorable=”d” d:DesignWidth=”640″ d:DesignHeight=”480″>


<Grid x:Name=”LayoutRoot” Background=”Azure”>


<Grid.RowDefinitions>


<RowDefinition Height=”400″/>


<RowDefinition Height=”*” />


</Grid.RowDefinitions>


<Image x:Name=”imgToDisplay” Height=”400″ Width=”300″ Source=”a.jpg”
Grid.Row=”0″/>


<StackPanel Orientation=”Horizontal” Grid.Row=”1″>


<RadioButton x:Name=”rdBtnLeft” Content=”Left” Click=”rdBtnName_Click”
HorizontalAlignment=”Right” />


<RadioButton x:Name=”rdBtnRight” Content=” Right” Click=”rdBtnName_Click”
HorizontalAlignment=”Right”/>


<RadioButton x:Name=”rdBtnUp” Content=”Up” Click=”rdBtnName_Click”
HorizontalAlignment=”Right”/>


<RadioButton x:Name=”rdBtndown” Content=”Down” Click=”rdBtnName_Click”
HorizontalAlignment=”Right” />


<Button x:Name=”btnRotate” Content=” Rotate” Click=”btnRotate_Click” HorizontalAlignment=”Center” Height=”65″ Width=”100″
/>


</StackPanel>


</Grid>

</UserControl>

 Code Behind

  1. Add same event for click on all radio buttons.
  2. In the click event of radio buttons, I am assigning sender’s name and checking it in a switch case.
    string
    radioButton = ((FrameworkElement)sender).Name;

    switch (radioButton)

{

}

 

  1. Rotation of image is being performed by RotateTransform class.


    RotateTransform rotate = new
    RotateTransform();

  2. In click event of Button we are checking radio button’s isChecked property. If IsChecked is true for a radio button it means that radio button is selected.


    if (rdBtnLeft.IsChecked == true)

    {

    }
     

MainPage.Xaml.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

namespace SilverlightApplication1

{


public
partial
class
MainPage : UserControl

{


int parameter = 0;


public MainPage()

{

InitializeComponent();

}
private
void rdBtnName_Click(object sender, RoutedEventArgs e)

{


RotateTransform rotate = new
RotateTransform();


string radioButton = ((FrameworkElement)sender).Name;


switch (radioButton)

{

case
“rdBtnLeft”:

rotate.Angle = 30;

imgToDisplay.RenderTransform = rotate;


break;


case
“rdBtnRight”:

rotate.Angle = 45;

imgToDisplay.RenderTransform = rotate;


break;


case
“rdBtnUp”:

rotate.Angle = 60;

imgToDisplay.RenderTransform = rotate;


break;


case
“rdBtndown” :

rotate.Angle = 360;

imgToDisplay.RenderTransform = rotate;


break;

}

}

 private
void btnRotate_Click(object sender, RoutedEventArgs e)

{


RotateTransform rotate = new
RotateTransform();


if (rdBtnLeft.IsChecked == true)

{

rotate.Angle = 30;

imgToDisplay.RenderTransform = rotate;

}


else
if (rdBtnRight.IsChecked == true)

{

rotate.Angle = 45;

imgToDisplay.RenderTransform = rotate;

}


else
if (rdBtnUp.IsChecked == true)

{

rotate.Angle = 60;

imgToDisplay.RenderTransform = rotate;

}


else

{

rotate.Angle = 90;

imgToDisplay.RenderTransform = rotate;

}}}}
Conclusion
In this article, I explained how to work with Radio Button control of Silver Light. I also explained how to rotate image in silver light. Thanks for reading .