C# 视图中未显示MVVM绑定
我在代码隐藏中设置数据上下文,并在XAML中设置绑定。 调试显示我的数据上下文是从我的模型填充的,但是这并没有反映在我的视图中 可能是一些简单的事情,但这已经困扰了我好几个小时了C# 视图中未显示MVVM绑定,c#,wpf,xaml,mvvm,datacontext,C#,Wpf,Xaml,Mvvm,Datacontext,我在代码隐藏中设置数据上下文,并在XAML中设置绑定。 调试显示我的数据上下文是从我的模型填充的,但是这并没有反映在我的视图中 可能是一些简单的事情,但这已经困扰了我好几个小时了 public partial class MainWindow : Window { public MainWindow(MainWindowVM MainVM) { this.DataContext = MainVM; InitializeComponent();
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"/>
公共部分类主窗口:窗口
{
公共主窗口(MainWindowVM MainVM)
{
this.DataContext=MainVM;
初始化组件();
}
}
公共类MainWindowVM:INotifyPropertyChanged
{
专用ICommand和m_按钮命令;
公共用户UserModel=新用户();
公共数据访问_DA=新数据访问();
公共MainWindowVM(字符串电子邮件)
{
UserModel=_DA.GetUser(UserModel,email);
//ButtonCommand=新的RelayCommand(新操作(显示消息));
}
}
公共类用户:INotifyPropertyChanged
{
私人内部ID;
私有字符串_FirstName;
私人字符串(姓氏),;
私人字符串\u电子邮件;
私有字符串\u ContactNo;
专用列表-分配的行;
公共字符串名
{
得到
{
返回_FirstName;
}
设置
{
_FirstName=值;
OnPropertyChanged(“名字”);
}
}
}
您正在将MainWindowVM
对象设置为DataContext
,该对象没有FirstName
属性
如果要绑定到用户的名字,需要指定路径UserModel.firstname
,就像在代码中访问它一样
因此,您的绑定应该如下所示:
<Label Content="{Binding Path=UserModel.FirstName}" HorizontalAlignment="Right" VerticalAlignment="Top" Padding="0,0,150,0"/>
您是否绑定到
UserModel
anywhere?Content=“{Binding Path=UserModel.FirstName}”否?我以前试过,只是再试一次,没有luck@DNKROZ您在输出窗口中看到任何错误消息吗?啊,是的,我看到BindingExpression路径错误:“在对象”“MainWindowVM”“上找不到UserModel”属性,但是,用户模型在MainWindowVM中定义为public@DNKROZ哦,我现在明白了。您必须将其定义为PropertyTankyou,只是得到一个错误“方法必须有一个返回类型”我需要像设置其他属性一样设置它吗?
public User UserModel { get; set; } = new User();