Datacontext does not work when I declare it in XAML. But the same works if set in Code.
Detailed Analysis.
My XAML
<Window x:Class="SimpleDatabindingwithclass.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" Name="windo">
<Grid DataContext="{Binding ElementName=windo,Path=objectOfStudent}">
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<TextBox Grid.Row="0" Margin="25" Height="25" Width="100" HorizontalAlignment="Left" Name="TextBox1" Text="{Binding Path=StudentName}"></TextBox>
</Grid>
</Window>
Corresponding code.
namespace SimpleDatabindingwithclass
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Student objectOfStudent = new Student();
objectOfStudent.StudentName = "John diley";
objectOfStudent.Address = "20, North Travilia, Washington DC.";
//not setting datacontext here since i set that in xaml
}
public class Student
{
private string studentname;
private string address;
public string Address
{
get { return address; }
set { address = value; }
}
public string StudentName
{
get{return studentname;}
set{studentname = value;}
}
}
}
}
But, the same when I use this XAML & set datacontext through code, it works!
ie, When I put something like
this.DataContext = objectOfStudent;
in MainWindow(), the application Works!
What do u think the problem is?
Binding only works with public properties, you can’t bind to some local variable. Make
objectOfStudentas public property of yourMainWindow.Edit:
Edit:
Also you need to implement INotifyPropertyChanged interface in the
MainWindowandStudentclasses and raisePropertyChangedwhen you set the properties. That is the right way, the binding will be updated everytime you change the properties. Or a simple way: createobjectOfStudentbefore callingInitializeComponent.