MVVM绑定未在视图中显示

DNK*_*ROZ 2 c# wpf datacontext xaml mvvm

我在后面的代码中设置我的数据上下文,并在XAML中设置绑定.调试显示我的数据上下文正在从我的模型填充,但这并没有反映在我的视图中.

可能是简单的事情,但这让我困扰了好几个小时.

 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"/>
Run Code Online (Sandbox Code Playgroud)

Dom*_*see 8

您将MainWindowVM对象设置为DataContext没有FirstName属性.

如果要绑定到用户的名字,则需要指定路径UserModel.FirstName,就像在代码中访问它一样.

所以你的绑定应该是这样的:

<Label Content="{Binding Path=UserModel.FirstName}" HorizontalAlignment="Right" VerticalAlignment="Top" Padding="0,0,150,0"/>
Run Code Online (Sandbox Code Playgroud)

此外,您需要定义UserModel属性而不是字段.

public User UserModel { get; set; } = new User();
Run Code Online (Sandbox Code Playgroud)