DNKROZ
DNKROZ

Reputation: 2852

MVVM Binding not showing in view

I am setting my data context in the code behind, and setting the bindings in the XAML. Debugging reveals that my data context is being populated from my model, however this is not being reflected in my view.

Probably something simple but this has been troubling me for hours.

 public partial class MainWindow : Window
{
    public MainWindow(MainWindowVM MainVM)
    {

        this.DataContext = MainVM;
        InitializeComponent(); 


    }
}

    public class MainWindowVM : INotifyPropertyChanged
{
    private ICommand m_ButtonCommand;
    public User UserModel = new User();
    public DataAccess _DA = new DataAccess();

    public MainWindowVM(string email)
    {
        UserModel = _DA.GetUser(UserModel, email);
        //ButtonCommand = new RelayCommand(new Action<object>(ShowMessage));
    }
  }


public class User : INotifyPropertyChanged
{
    private int _ID;
    private string _FirstName;
    private string _SurName;
    private string _Email;
    private string _ContactNo;

    private List<int> _allocatedLines;

    public string FirstName
    {
        get
        {
            return _FirstName;
        }
        set
        {
            _FirstName = value;
            OnPropertyChanged("FirstName");
        }
    }
   }



 <Label Content="{Binding Path=FirstName}" HorizontalAlignment="Right" VerticalAlignment="Top" Padding="0,0,150,0"/>

Upvotes: 4

Views: 2497

Answers (1)

Domysee
Domysee

Reputation: 12846

You are setting a MainWindowVM object as DataContext, which does not have a FirstName property.

If you want to bind to the firstname of the user, you need to specify the path UserModel.FirstName, as if you were accessing it in code.

So your binding should look like this:

<Label Content="{Binding Path=UserModel.FirstName}" HorizontalAlignment="Right" VerticalAlignment="Top" Padding="0,0,150,0"/>

Additionally, you need to define UserModel as property instead of a field.

public User UserModel { get; set; } = new User();

Upvotes: 8

Related Questions