Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » Silverlight » XAML and C# within a Silverlight 2 context - Binding process: Part II

XAML and C# within a Silverlight 2 context - Binding process: Part II

In this article, I will show different techniques to interact with a given XAML UI with a C# code behind object.

Author Rank :
Page Views : 4878
Downloads : 55
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
Bejaoui.zip
 
 
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


As a response for the first question posed as a part of the first part of the article How does an XAML interface interact with C# code behind within a Silverlight 2 context: Part I. I will provide real use case scenarios of binding between source object written in C# and XAML UI

Scenario 1: Create a binding within XAML code zone

It is quite simple to bind a C# code behind object to an XAML UI, but some rules should be respected. Let's consider this XAML UI:

<UserControl xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data" x:Class="Silverlight.Page" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="300" Height="300">
    <Grid x:Name="LayoutRoot" Background="Azure" >
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="80"/>
            <ColumnDefinition Width="80"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="20"/>
            <RowDefinition Height="20"/>
            <RowDefinition Height="20"/>
        </Grid.RowDefinitions>
        <TextBlock Grid.Column="0" Grid.Row="0"> First name</TextBlock>
        <TextBlock Grid.Column="1" Grid.Row="0"> Last name</TextBlock>
        <TextBlock x:Name="txtFirstName" Grid.Column="0" Grid.Row="1" Text= "Bejaoui" />
        <TextBlock x:Name="txtLastName" Grid.Column="1" Grid.Row="1" Text="Bechir" />
    </Grid>
</
UserControl>

The result of this XAML is



Figure 1

Ok, what if I want to provide the data "Bejaoui" and "Bechir" from a given C# object, what's should I do?

Well, first let's define a Person object in the C# code behind

public class Person
{
   public Person()
 {
 }  
public
Person(string FirstName, string LastName)
   {    
     this
.FirstName = FirstName;
     this.LastName = LastName;
   }  
     public
string FirstName
     {
        get
; set;
     }  
    public
string LastName
     {
        get
; set;
     }
     }

The class must be public and must have at least a parameter less constructor otherwise a run time error will be raised.

Then we switch to the XAML code editor and we add a reference to our namespace, In this case, my customized namespace that holds the Person object is called Silverlight.



Figure 2

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

The word code is chosen arbitrary, you can use whatever you want as keyword, but once it is set it will be used to reference your namespace until the end of the project. Of Corse you can change it, but you have the obligation to change all the old keywords by the new ones throughout the entire project.

The next step is to create the resources for the both TextBlocks. We add a new tag for that purpose

<Grid.Resources></Grid.Resources>

Those above tags should be nested within the Main container which is a Grid control in our case. Now, we can add a code as it is recognized now by the environment



Figure 3

Say that I want to create a person, first I have to give it an identifier through x:Name attribute, else a runtime error will be raised later when running the application.

<Grid.Resources>
        <code:Person x:Name="me" FirstName="Bejaoui" LastName="Bechir"/>
    </Grid.Resources>

At the other hand, the Text attribute of the both TextBlocks should be set as follow:

     <TextBlock x:Name="txtFirstName" Grid.Column="0" Grid.Row="1" Text= "{Binding FirstName,Source={StaticResource me}}" />
        <TextBlock x:Name="txtLastName" Grid.Column="1" Grid.Row="1" Text="{Binding LastName,Source={StaticResource me}}" />

As you can remark, the Binding attribute targets the object property and the StaticResource should refer to the given Person instance and therefore x:Name of the person instance should be set to a value that will be used as a reference.

This is the resulting XAML code:

<UserControl xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data" x:Class="Silverlight.Page" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:code="clr-namespace:Silverlight" Width="300" Height="300">
    <Grid x:Name="LayoutRoot" Background="Azure" >
        <Grid.Resources>
            <code:Person x:Name="me" FirstName="Bejaoui" LastName="Bechir"/>
        </Grid.Resources>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="80"/>
            <ColumnDefinition Width="80"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="20"/>
            <RowDefinition Height="20"/>
            <RowDefinition Height="20"/>
        </Grid.RowDefinitions>
        <TextBlock Grid.Column="0" Grid.Row="0"> First name</TextBlock>
        <TextBlock Grid.Column="1" Grid.Row="0"> Last name</TextBlock>
        <TextBlock x:Name="txtFirstName" Grid.Column="0" Grid.Row="1" Text= "{Binding FirstName,Source={StaticResource me}}" />
        <TextBlock x:Name="txtLastName" Grid.Column="1" Grid.Row="1" Text="{Binding LastName,Source={StaticResource me}}" />
    </Grid>
</
UserControl>

The result will be



Figure 4

Suppose now that I want to add a new member to the class Person, should this be reflected at the XAML level?

The response is simply yes. Say that the Person class will be modified as follow

public class Person   
{
        public Person()
 {
 }
        public Person(string FirstName, string LastName, string PseudoName)
        {  
            this.FirstName = FirstName;
            this.LastName = LastName;
            this.PseudoName = PseudoName;
         }
             public string FirstName
              {
                 get; set;
              }


If we move to the XAML side and try to verify that



Figure 5

Well, the rest is to configure the XAML UI so that it provides a place to the new coming value

<UserControl xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data" x:Class="Silverlight.Page" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:code="clr-namespace:Silverlight" Width="300" Height="300">
    <Grid x:Name="LayoutRoot" Background="Azure" >
        <Grid.Resources>
            <code:Person x:Name="me" FirstName="Bejaoui" LastName="Bechir" PseudoName="Yougethen"/>
        </Grid.Resources>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="80"/>
            <ColumnDefinition Width="80"/>
            <ColumnDefinition Width="80"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="20"/>
            <RowDefinition Height="20"/>
            <RowDefinition Height="20"/>
        </Grid.RowDefinitions>
        <TextBlock Grid.Column="0" Grid.Row="0"> First name</TextBlock>
        <TextBlock Grid.Column="1" Grid.Row="0"> Last name</TextBlock>
        <TextBlock Grid.Column="2" Grid.Row="0"> Pseudo name</TextBlock>
        <TextBlock x:Name="txtFirstName" Grid.Column="0" Grid.Row="1" Text= "{Binding FirstName,Source={StaticResource me}}" />
        <TextBlock x:Name="txtLastName" Grid.Column="1" Grid.Row="1" Text="{Binding LastName,Source={StaticResource me}}" />
        <TextBlock x:Name="txtPseudoName" Grid.Column="2" Grid.Row="1" Text="{Binding PseudoName,Source={StaticResource me}}" />
    </Grid>
</
UserControl>

Then the result will be:



Figure 6

Finally, what if I want to get an instance of that Person "me" as it is defined within the XAML side? Well, it is also a kid joke. You simply get the person instance by writing this simple C# line code,

Silverlight.Person Ich = LayoutRoot.Resources["me"] as Silverlight.Person;

Of Corse, the "LayoutRoot" is supposed to be the key name of the main container which is the grid control

<Grid x:Name="LayoutRoot"
Background="Azure

The C# instance has to have a different name than the used key within the XAML side, so "Ich" is different to "me", otherwise and error will be raised later.

Finally, if you have an XAML defined control and you want to handle it from within C# code then it is easier that a kid joke. Suppose that you have a textbox named "txtFirstName" within your XAML UI and you want to get an instance of it then you simply define a TextBox as follow:

TextBox instance = LayoutRoot.FindName("txtFirstName") as TextBox;

In the next article, we will show more techniques of binding process, so don't miss the next article how does an XAML interface interact with C# code behind within a Silverlight 2 context? -Binding Process-Part III, that's it.

Good Dotneting!!!

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Bechir Bejaoui

The author holds a master degree in NTIC specialized  in software developement delivered by the high school of communication SUPCOM, he also holds a bachelor degree in finance delivered by  the  economic sciences and  management  university of Tunis "FSEGT".

He also holds:

MCPD enteprise solutions developement 3.5 certification and MCTS distibuted application developement 2.0

 He's a freelance developer since 2006. Actually woking on the WPF, .Net framewok 3.5, silverlight and the other .Net new features, in addition, he is painter and sculptor.

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
You're great Bechir!!!! by Name On January 9, 2009
You're great Bechir, I Have look after in the internet for this solution but I have never found a sufficient solution to my problem anywhere but this article respond exactly to my requirements now I can create interaction between C# And XAML thank you
Reply | Email | Modify 
Re: You're great Bechir!!!! by Bechir On February 2, 2009

Not at all.
Reply | Email | Modify 
6 Months Free & No Setup Fees ASP.NET Hosting!
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.