Software & Finance





WPF TextBox Binding – DataContext and Overriding DataContext for a specific object





I have explained here about WPF textbox binding and datacontent with example.

I have Grid name “MyGrid” that contains TextBox controls. I have the DataContext of Grid to CurrentStudent. Now two TextBox controls with in MyGrid, will have default DataContext as CurrentStudent. For these two TextBox controls, I have set binding path as Name and City respectively. Now the text box controls will depend on the data context CurrentStudent.
In .cs file, when you want to get the values, you can have the following code: Note that “MyGrid” is the gui name of the Grid Control in xaml file.

 

StudentInformation source = (StudentInformation)MyGrid.DataContext;

 

If I want to change the data context for the City TextBox, I can override the settings as follows:

<TextBox Name="gui_studentCity" Width="220" DataContext="{StaticResource AnotherStudent}"  Text="{Binding Path=City, Mode=TwoWay}"></TextBox>

 

 

Here is the complete xaml code and .cs file.

 

<Window x:Class="ListBoxDemo.StudentInformationWindow"

    xmlns:mynamespace="clr-namespace:ListBoxDemo"

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

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

    Title="Student Information Management" Height="370" Width="330">

  

<Grid Name="MyGrid">

 

      <Grid.Resources>

         <mynamespace:StudentInformation x:Key="CurrentStudent"/>

         <mynamespace:StudentInformation x:Key="AnotherStudent"/>

      </Grid.Resources>

      <Grid.DataContext>

         <Binding Source="{StaticResource CurrentStudent}"/>

     </Grid.DataContext>

     

      <Grid.RowDefinitions>

         <RowDefinition Height="70"></RowDefinition>

         <RowDefinition Height="35"></RowDefinition>

         <RowDefinition Height="*"></RowDefinition>

      </Grid.RowDefinitions>

      

       <StackPanel Orientation="Vertical" Grid.Row="0">

         <TabPanel Margin="0,5,0,0">

            <Label Content="Name:" Width="50"></Label>

            <TextBox Name="gui_studentName" Width="220" Text="{Binding Path=Name, Mode=TwoWay}"></TextBox>

         </TabPanel>

          <TabPanel Margin="0,10,0,0">

            <Label Content="City:" Width="50"></Label>

            <TextBox Name="gui_studentCity" Width="220" DataContext="{StaticResource AnotherStudent}"  Text="{Binding Path=City, Mode=TwoWay}"></TextBox>

      </StackPanel>

</Grid>

<Button Name="Add" Content="Add" Click="Add_Click" Width="50" Height="24" Margin="10,0,0,0" HorizontalAlignment="Center"  VerticalAlignment="Center"></Button>

 

namespace ListBoxDemo

{

public partial class StudentInformationWindow : Window

   {

private void Add_Click(object sender, RoutedEventArgs e)

      {

StudentInformation source = (StudentInformation)MyGrid.DataContext;              MessageBox.Show(source.ToString());

      }

 

public class StudentInformation : INotifyPropertyChanged

      {

      public string _name;

      public string _city;

 

      public event PropertyChangedEventHandler PropertyChanged;

 

      protected void NotifyPropertyChanged(string property)

      {

         if (PropertyChanged != null)

         {

            PropertyChanged(this, new PropertyChangedEventArgs(property));

         }

      }

 

      public string Name

      {

         get

         {

            return _name;

         }

         set

         {

            _name = value; NotifyPropertyChanged("Name");

         }

      }

 

      public string City

      {

         get

         {

            return _city;

         }

         set

         {

            _city = value; NotifyPropertyChanged("City");

         }

      }

 

      public override string  ToString()

      {

            return Name + " " + City;

      }

   }

}


WPF Creating Instance of a class in xaml file and mapping properties to UI controls for binding

Under resources section, we can create objects (instance of a class) and use it as a DataContext for the UI controls in xaml.

Implement a class in C# code:

namespace ListBoxDemo

{

public class StudentInformation

{

            public string Name { get; set; };

      public string City { get; set; };

}

}

Note that I have inserted “mynamespace” newly into the xaml code. Under Window.Resources tag, I am creating an instance named “CurrentStudent” for the class StudentInformation – hilighted in green. Then datacontext the window class StudentInformationWindow set with Window.DataContext tag – hilighted in light blue.

Finally the TextBox controls are using the {Binding Path=Name} and {Binding Path=City}, which are the property of the Window.DataContext, that is instance of the class StudentInformation, that is CurrentStudent object.

<Window x:Class="ListBoxDemo.StudentInformationWindow"

    xmlns:mynamespace="clr-namespace:ListBoxDemo"

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

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

    Title="Student Information Management" Height="370" Width="330">

<Window.Resources>

      <mynamespace:StudentInformation x:Key="CurrentStudent"/>

</Window.Resources>

<Window.DataContext>

      <Binding Source="{StaticResource CurrentStudent}"></Binding>

</Window.DataContext>

 

<TextBox Name="gui_studentName" Width="220" Text="{Binding Path=Name, Mode=TwoWay}"></TextBox>

<TextBox Name="gui_studentCity" Width="220" Text="{Binding Path=City, Mode=TwoWay}"></TextBox>

 

</Window>