2016-03-08 71 views
3

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

大概是简单的,但这一直困扰着我好几个小时。

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"/> 
+0

您是否在任何地方绑定到'UserModel'? – Domysee

+0

Content =“{Binding Path = UserModel.FirstName}”否? – tim

回答

7

您设置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(); 
+0

我之前试过,只是再试过一次,没有运气 – DNKROZ

+0

@DNKROZ你看到输出窗口中有错误信息吗? – Domysee

+0

啊是的,我做的BindingExpression路径错误:'对象'找不到'UserModel'属性'''MainWindowVM' 但是,UserModel在MainWindowVM中定义为public – DNKROZ