Saturday, 24 August 2013

DOTNET WPF XAML C# USING DATACONTEXT MANOHAR GOUD TRAINER FACULTY GURU DEVELOPER

K. MANOHAR GOUD


DOTNET WPF XAML C# USING DATACONTEXT

The DataContext property sets the basis of all binding down through the hierarchy of controls .This saves you from the problem of manually defining the source of each binding, hence it saves time. Rather than defining the source multiple times for binding. It also improves object oriented code readability.
Let's try illustrating it with a simple example.

Step 1
 

First we create a WPF application using the following procedure:
  • Open Visual Studio.
  • Select the C# language and "WPF Application".
  • Name the project "DataContext".
  • Click on the "OK" button.
first.jpg
Step 2
  • Now go to the MainWindow.xaml.
  • Delete the Grid tag.
  • Write the following code in MainWindow.xaml:
<Window x:Class="WpfApplication14.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel Margin="15" Width="452" Background="#FFDED022">
        <WrapPanel>
            <Label Content ="Window Title:  " />
            <TextBox Text="{Binding Title, UpdateSourceTrigger=PropertyChanged}" Width="200" />
        </WrapPanel>
        <WrapPanel Margin="0,10,0,0">
            <Label Content="Window Dimensions: " />
            <TextBox Text="{Binding Width}" Width="100" />
            <Label Content =" x " />
            <TextBox Text="{Binding Height}" Width="100" />
        </WrapPanel>
    </StackPanel>
</Window>
  • Corresponding to the code above the window looks as:
123.jpg
Step 3
  • Now go to the MainWindow.xaml.cs.
  • Write the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication14
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
      
  
     public MainWindow()
                {
                        InitializeComponent();
                        this.DataContext = this;
                }
        }
}
Output 
Press F5.
 Clipboard02.jpg 
 





No comments:

Post a Comment