Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Gauge for SharePoint
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » Silverlight » Data Access and Data Binding in Silverlight Controls using WCF Service

Data Access and Data Binding in Silverlight Controls using WCF Service

In this article I will discuss how to bind data to Silverlight controls and access data in Silverlight 2 using WCF Service.

Author Rank :
Page Views : 10483
Downloads : 201
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:
SilverlightApplication4.zip
 
 
Nevron Gauge for SharePoint
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Data binding is a connection between the User Interface and a business object or other data provider. The data binding capabilities of XAML and Silverlight offer more power and flexibility with less runtime code. The User Interface object is called the target; the provider of the data is called the source. When binding the data keep the few things in mind

  1. The target of data binding must be a System.Windows.FrameworkElement. Control that derives from FrameworkElement can be used for layout on a page or user control.
  2. The target must be a Dependency Property.  Dependency Properties are data-bound properties whose value is determined at runtime using an order of precedence.
  3. The Mode (which is of type BindingMode) is an enumeration with three possible values
    OneTime binding sets the target and then the binding is completed. Useful for displaying data that rarely or never changes
    OneWay binding sets the target and keeps it up to date as the source changes. Useful for displaying data that the user is not permitted to change.
    TwoWay binding sets the target and keeps the target up to date as the source changes and keeps the source up to date as the user changes the target or changes something else in the application that will cause application to change the source.
  4. The DataContext refers to a source of data that can be bound to a target. The DataContext often is set to an instance of an entity. It can be used to bind all controls within a container control to a single data source.

Now let's create a simple application.

  1. Create a Silverlight application in visual studio 2008
  2. Add Linq to SQL Classes in App_Code folder of your web project.

  1. Add the database object you want to access in the application.
     
  2. Add WCF Service to the Web Project.

 

  1. Update IService.cs as below.

[ServiceContract]

public interface IService

{

    [OperationContract]

    List<User> GetUsers(string FirstName);

}

  1. Update Service.cs as below to implement the IService.

public class Service : IService

{

    public List<User> GetUsers(string FirstName)

    {

        DataClassesDataContext db = new DataClassesDataContext();

        var matchingCustomers = from cust in db.Users

                                where cust.FirstName.StartsWith(FirstName)

                                select cust;

        return matchingCustomers.ToList();

    }

}

  1. Change service enpoint binding from wsHttpBinding to basicHttpBinding in web.congif.

<services>

   <service behaviorConfiguration="ServiceBehavior" name="Service">

         <endpoint address="" binding="basicHttpBinding" contract="IService">

         <identity>

               <dns value="localhost"/>

         </identity>

         </endpoint>

   </service>

</services>

  1. Add Service reference of the WCF Service in Silverlight Project.

  1. Create the Page.xaml with TextBox, Button and DataGrid as below

<UserControl xmlns:my="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"  x:Class="SilverlightApplication4.Page"

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

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

    Width="700" Height="500">

    <Grid x:Name="LayoutRoot" Background="White" ShowGridLines="False">

        <Grid.RowDefinitions>

            <RowDefinition Height="10" />

            <RowDefinition Height="50" />

            <RowDefinition Height="*" />

            <RowDefinition Height="10" />

        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>

            <ColumnDefinition Width="10" />

            <ColumnDefinition Width="*" />

            <ColumnDefinition Width="10" />

        </Grid.ColumnDefinitions>

        <Border BorderBrush="Black" BorderThickness="2" Grid.Row="1" Grid.Column="1"/>

        <StackPanel Grid.Row="1" Grid.Column="1" Orientation="Horizontal">

            <TextBlock Text="Name: " VerticalAlignment="Bottom" FontSize="18" Margin="15,0,0,0" />

            <TextBox x:Name="FirstName" Width="250" Height="30" Margin="2,0,0,4" VerticalAlignment="Bottom"/>

            <Button x:Name="Search" Width="75" Height="30" Margin="20,0,0,4" Content="Search" VerticalAlignment="Bottom"  Background="Blue" FontWeight="Bold" FontSize="14" Click="Search_Click" />

        </StackPanel>

        <my:DataGrid x:Name="DataGrid1" AlternatingRowBackground="Beige" AutoGenerateColumns="False" Width="700" Height="300" Grid.Row="2" Grid.Column="1" CanUserResizeColumns="True">

            <my:DataGrid.Columns>

                <my:DataGridTextColumn

                    Header="First Name"

                    Width="120"

                    DisplayMemberBinding="{Binding FirstName}"

                    FontSize="11" />

                <my:DataGridTextColumn

                    Header="Last Name"

                    Width="120"

                    DisplayMemberBinding="{Binding LastName}"

                    FontSize="11" />

            </my:DataGrid.Columns>

        </my:DataGrid>

    </Grid>

</UserControl>

  1. Add Search Button event handeler to Page.xaml.cs

private void Search_Click(object sender, RoutedEventArgs e)

        {

            ServiceReference1.ServiceClient webService = new ServiceReference1.ServiceClient();

            webService.GetUsersCompleted += new EventHandler<ServiceReference1.GetUsersCompletedEventArgs>(webService_GetUsersCompleted);

            webService.GetUsersAsync(FirstName.Text);

        }

        void webService_GetUsersCompleted(object sender, ServiceReference1.GetUsersCompletedEventArgs e)

        {

            DataGrid1.ItemsSource = e.Result;

        }

  1. Run the Appliation and you can see the screen as below

Type the name and press the search button, the results will be displayed in the datagrid.

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
 
Nipun Tomar

Nipun is competent and experienced "project leader", with "8 years" of experience in managing multi-disciplinary teams of varying sizes and complex programs of work. Has the ability to build strong relationships with all stakeholders and to turn proposals into reality.

"Especially successful in management roles that demand rigor, a high level of drive and dedication and a focus on delivering business outcomes through the use of methodologies".

Strengths include successful analysis and problem-solving expertise, highly rated oral and written communications skills, and proven project management experience. Strong background in "C#, Visual Studio 2010, ASP.NET, Windows Forms, WPF, WCF, Silverlight and SQL Server".

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.
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:
Nevron Gauge for SharePoint
Become a Sponsor
 Comments
Thanks by X On September 30, 2008

Thank you, great article!

Greetings from Hungary!

Reply | Email | Modify 
Re: Thanks by Nipun On October 20, 2008
Glad to hear that it was helpful and you liked the article. Thanks..
Reply | Email | Modify 
Help regarding multiple table data access by moein On September 15, 2010
Dear Nipun,

I want to know how can I add multiple table to linq to sql classes (dbml) and use service to retrieve and access data from multiple table in one datagrid ur help would be appriciate thanks in advance
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.