|
|
|
|
|
Home
»
Silverlight
»
XAML and C# within a Silverlight 2 context - Binding process: Part II
|
|
|
Author Rank:
|
|
Total page views :
2919
|
|
Total downloads :
38
|
|
|
|
|
Download
Files:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Similar ArticlesMost ReadTop RatedLatest
|
|
|
|
|
|
|
|
|
|
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!!!
|
|
|
Login
to add your contents and source code to this article
|
|
|
|
|
|
|
|
|
|
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'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.
|
|
|
|
|
|
|
|
|
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.
|
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
|
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today. With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications. Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
|
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or
application via a range of API's. Learn More about our API connections.
|
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
|
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.
|
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
|
|
|
|
|
|
|
|
|
Download
Files:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|