【问题标题】:MVVM Binding not showing in viewMVVM 绑定未显示在视图中
【发布时间】:2016-06-23 01:24:49
【问题描述】:

我在后面的代码中设置我的数据上下文,并在 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"/>

【问题讨论】:

  • 你在任何地方绑定到UserModel吗?
  • Content="{Binding Path=UserModel.FirstName}" 没有?

标签: c# wpf xaml mvvm datacontext


【解决方案1】:

您将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();

【讨论】:

  • 我之前尝试过,只是再次尝试,没有成功
  • @DNKROZ 您在输出窗口中看到任何错误消息吗?
  • 啊,是的,我做 BindingExpression 路径错误:在 'object' ''MainWindowVM' 上找不到 'UserModel' 属性 但是,在 MainWindowVM 中将 UserModel 定义为公共
  • @DNKROZ 哦,我现在明白了。您必须将其定义为属性
  • 谢谢,刚刚收到一个错误“方法必须有返回类型”,我需要像我的其他属性一样设置它吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-01
相关资源
最近更新 更多