Hi everyone,
I'm relatively new to WPF and MVVM, and I'm struggling with setting up the data binding between my main window and its corresponding ViewModel. I've created a simple ViewModel with a few properties, but I can't seem to get the binding to work. I've tried setting the DataContext in XAML and in code-behind, but the UI elements aren't updating, nor are they reflecting the initial values from the ViewModel.
Here's a simplified example of my setup:
MainWindow.xaml:
// MainWindow.xaml
MainWindowViewModel.cs:
// MainWindowViewModel.cs
using System.ComponentModel;
namespace MyWpfApp
{
public class MainWindowViewModel : INotifyPropertyChanged
{
private string _windowTitle = "Default Title";
public string WindowTitle
{
get { return _windowTitle; }
set
{
_windowTitle = value;
OnPropertyChanged(nameof(WindowTitle));
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
And in my MainWindow.xaml.cs constructor:
// MainWindow.xaml.cs
public MainWindow()
{
InitializeComponent();
DataContext = new MainWindowViewModel();
}
What am I missing? Is there a common pitfall I should be aware of?