MVVM绑定在视图中未显示

4
我正在代码后台设置数据上下文,并在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 - Domysee
内容="{Binding Path=UserModel.FirstName}" 对吗? - timr
1个回答

8

你正在将一个没有 FirstName 属性的 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();

啊是的,我遇到了 BindingExpression 路径错误:在 'MainWindowVM' 的 'object' 上未找到 'UserModel' 属性。但是,UserModel 在 MainWindowVM 中被定义为公共属性。 - DNKROZ
@DNKROZ 哦,我现在明白了。你必须将其定义为属性。 - Domysee
谢谢,我刚刚遇到了一个错误:“方法必须有返回类型”,我需要像其他属性一样设置它吗? - DNKROZ
@DNKROZ 是的,就像任何其他属性一样。最好在setter中引发PropertyChanged事件。 - Domysee
谢谢,我现在会尝试一下。 - DNKROZ
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接