I am a reasonably experienced programmer but new to WPF. I have bound a textblock on a form to an object property, but it is not updating the form as I would expect when I set the property. The binding appears to be done correctly–if I troubleshoot with a button that updates the property the form changes, but when I initially set the property in the form’s constructor by parsing a local XML file it doesn’t update.
I am using C# and VS2010. Could someone guide me for a few steps or refer me to a book or coding tool that gets me over this hump. Also, please note that I chose to structure things way by imitating the paradigm used in the “How Do I: Build My First WPF Application” at windowsclient.net. If you think I’m going about it the wrong way, I would appreciate a pointer to a better tutorial.
Form XAML:
<Window ...
xmlns:vm="clr-namespace:MyProjectWPF.ViewModels">
<Grid>
<Grid.DataContext>
<vm:MyConfigurationViewModel />
</Grid.DataContext>
<TextBlock Name="textBlock4" Text="{Binding Path=Database}" />
</Grid>
MyConfigurationViewModel class definition:
class MyConfigurationViewModel : INotifyPropertyChanged
{
private string _Database;
public string Database
{
get { return _Database; }
set { _Database = value; OnPropertyChanged("Database"); }
}
public void LoadConfiguration()
{
XmlDocument myConfiguration = new XmlDocument();
myConfiguration.Load("myfile.xml");
XmlNode root = myConfiguration.DocumentElement;
Database = root["Database"].InnerText;
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string Property)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(Property));
}
And the codebehind my XAML form:
public partial class MyForm : Window
{
private ViewModels.myConfigurationViewModel mcvm
= new ViewModels.myConfigurationViewModel();
public MyForm()
{
mcvm.LoadConfiguration();
}
You have two instances of myConfigurationViewModel. One is created inside the XAML and the second one is created inside the form’s codebehind. You are calling LoadConfiguration on the one in the code behind, which is never set as the form’s DataContext.
Remove this from the XAML:
and change the constructor to this: