MVVM 绑定未显示在视图中
MVVM Binding not showing in view
我在后面的代码中设置我的数据上下文,并在 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"/>
您将 MainWindowVM
对象设置为 DataContext
,它没有 FirstName
属性。
如果您想绑定到用户的名字,您需要指定路径 UserModel.FirstName
,就像您在代码中访问它一样。
因此您的绑定应如下所示:
<Label Content="{Binding Path=UserModel.FirstName}" HorizontalAlignment="Right" VerticalAlignment="Top" Padding="0,0,150,0"/>
此外,您需要将 UserModel
定义为 属性 而不是字段。
public User UserModel { get; set; } = new User();
我在后面的代码中设置我的数据上下文,并在 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"/>
您将 MainWindowVM
对象设置为 DataContext
,它没有 FirstName
属性。
如果您想绑定到用户的名字,您需要指定路径 UserModel.FirstName
,就像您在代码中访问它一样。
因此您的绑定应如下所示:
<Label Content="{Binding Path=UserModel.FirstName}" HorizontalAlignment="Right" VerticalAlignment="Top" Padding="0,0,150,0"/>
此外,您需要将 UserModel
定义为 属性 而不是字段。
public User UserModel { get; set; } = new User();