Reputation: 1316
I am new to WPF
. I have developed this test MVVM
Application using WPF
. But binding does not work. But as far as my knowledge no errors can be detected. can any one help on this. below images and coding shows the test app.
Student.cs
using System;<br/>
using System.Collections.Generic;<br/>
using System.Linq;<br/>
using System.Text;
using System.ComponentModel;
namespace WpfNotifier
{
public class Student : INotifyPropertyChanged
{
private string _name;
public string Name
{
get { return this._name; }
set
{
this._name = value;
this.OnPropertyChanged("Name");
}
}
private string _company;
public string Company
{
get { return this._company; }
set
{
this._company = value;
this.OnPropertyChanged("Company");
}
}
private string _designation;
public string Designation
{
get { return this._designation; }
set
{
this._designation = value;
this.OnPropertyChanged("Designation");
}
}
private Single _monthlypay;
public Single MonthlyPay
{
get { return this._monthlypay; }
set
{
this._monthlypay = value;
this.OnPropertyChanged("MonthlyPay");
this.OnPropertyChanged("AnnualPay");
}
}
public Single AnnualPay
{
get { return 12 * this.MonthlyPay; }
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
Upvotes: 0
Views: 7342
Reputation: 22435
binding just work for public properties, so your
<Grid DataContext="{Binding Path=st}">
did not work. you have to set this.DataContext = this; in your MainWindow ctor. btw why do you need a static student object?
public MainWindow()
{
...
this.DataContext = this;
}
with this code your datacontext is your mainwindow and now your binding can work.
to check DataContext and Bindings at runtime you can use Snoop.
Upvotes: 2
Reputation: 33242
Try to attach the Student
instance sc
to the window DataContext
.
In the MainWindow
contructor add the line:
this.DataContext=sc;
Many mvvm library can sort of do this automtically. Without any of this you can define an embedded resource of type Student and set it to the DataContext of the window. But as a suggestion, if you want to start with MWWM, try some already made OSS library.
Upvotes: 1
Reputation: 629
In the code-behind(xaml.cs) file after the InitailizeComponent();
statement add the following piece of code:
this.DataContext=new Student();
Add the default constructor in Student.cs
public Student()
{
}
Upvotes: 0