c# - MVVM 绑定(bind)未显示在 View 中

标签 c# wpf xaml mvvm datacontext

我在后台代码中设置我的数据上下文,并在 XAML 中设置绑定(bind)。 调试显示我的数据上下文是从我的模型中填充的,但这并没有反射(reflect)在我的 View 中。

可能是一些简单的事情,但这困扰了我几个小时。

 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 属性。

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

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

<Label Content="{Binding Path=UserModel.FirstName}" HorizontalAlignment="Right" VerticalAlignment="Top" Padding="0,0,150,0"/>

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

public User UserModel { get; set; } = new User();

关于c# - MVVM 绑定(bind)未显示在 View 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35878565/

相关文章:

c# - 拉普拉斯滤波器的掩码尺寸更大?

wpf - 使用元素语法设置 UserControl 上的附加属性值

c# - XAML 重用标记 block

wpf - XAML 智能感知不适用于引用的程序集资源

c# - 在 Windows Phone 8 应用程序中更改全景标题

C# SQL 查询产生与 Management Studio 不同的结果

c# - 正确的连接字符串语法

c# - 接受按钮不起作用

wpf - 将 WPF 控件调整为精确的百分比

c# - 从绑定(bind)到我的 XAML 中的事件调用我的 ViewModel 中的命令?