Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"/>
like image 274
DNKROZ Avatar asked Feb 07 '23 13:02

DNKROZ


1 Answers

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();
like image 63
Domysee Avatar answered Feb 11 '23 20:02

Domysee