DataBinding in WPF using DataContext in XAML
DataBinding in WPF using DataContext in XAML
EmpViewModel.cs
namespace SampleApplication
{
public class EmpViewModel
{
private int empID;
public int EmpID
{
get
{
return 123;
}
set
{
empID = value;
}
}
private string empName;
public string EmpName
{
get
{
return "ABC";
}
set
{
empName = value;
}
}
}
}
After this class, I have following XAML file(MainWindow.xaml) which contains two textboxes to which I want to bind the EmpID and EmpName properties.
MainWindow.xaml
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
I will have to make some changes/additions to this XAML file to bind the EmpID and EmpName properties to the above textboxes.
1. First of all, I will have to add a xaml namespace like following:
xmlns:local="clr-namespace:SampleApplication"
2. Now, I have to add DataContext:
3. Finally, I have to bind properties to the textboxes:
My final xaml will look like this:
MainWindow.xaml
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SampleApplication"
Title="MainWindow" Height="350" Width="525">
Text="{Binding EmpID}" />
Text="{Binding EmpName}" />
I would like to share a very simple example of databinding in WPF using DataContext in XAML file. In this WPF databinding simple example, I have a class named EmpViewModel which has two properties EmpID and EmpName. I will bind these EmpID and EmpName properties with two textboxes in the XAML file. Following is my EmpViewModel class under SampleApplication namespace:
EmpViewModel.cs
namespace SampleApplication
{
public class EmpViewModel
{
private int empID;
public int EmpID
{
get
{
return 123;
}
set
{
empID = value;
}
}
private string empName;
public string EmpName
{
get
{
return "ABC";
}
set
{
empName = value;
}
}
}
}
After this class, I have following XAML file(MainWindow.xaml) which contains two textboxes to which I want to bind the EmpID and EmpName properties.
MainWindow.xaml
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
I will have to make some changes/additions to this XAML file to bind the EmpID and EmpName properties to the above textboxes.
1. First of all, I will have to add a xaml namespace like following:
xmlns:local="clr-namespace:SampleApplication"
2. Now, I have to add DataContext:
3. Finally, I have to bind properties to the textboxes:
My final xaml will look like this:
MainWindow.xaml
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SampleApplication"
Title="MainWindow" Height="350" Width="525">