英文:
Error in Databinding a property to a label in WPF
问题
我要构建一个基本的WPF应用程序;我无法在MainView中显示学生姓名("Alexa")。以下是我的代码详细信息:
我在Model中有一个Student.cs类,如下所示
namespace Client.Model
{
class Student:INotifyPropertyChanged
{
private string _name = "Alexa";
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged(nameof(Name));
}
}
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler? PropertyChanged;
}
}
而MainViewModel.cs如下所示
class MainViewModel: ViewModelBase
{
private Student _student;
public Student Student
{
get { return _student; }
set {
if (_student != value)
{
_student = value;
}
OnPropertyChanged("Student");
}
}
}
在我的MainView中,我尝试显示学生姓名如下:
<Label FontStyle="Italic">学生姓名是:</Label>
<Label FontStyle="Italic" Content="{Binding Student.Name}"></Label>
同时,我在MainView.cs中设置了
this.DataContext = new MainViewModel();
我漏掉了什么吗?
英文:
I am to build basic application in wpf; I am not able to display student name ("Alexa") in the MainView. Here are my code details:
I have a Student.cs class in Model as shown
namespace Client.Model
{
class Student:INotifyPropertyChanged
{
private string _name ="Alexa";
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged(nameof(Name));
}
}
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler? PropertyChanged;
} }
And MainViewModel.cs is
class MainViewModel: ViewModelBase
{
public Student Student
{
get { return _student; }
set {
if (_student != value)
{
_student = value;
}
OnPropertyChanged("_student");
}
}
}
In my MainView, I am trying to display the student name as
<Label FontStyle="Italic" >Student Name is:</Label>
<Label FontStyle="Italic" Content="{Binding Student.Name}" ></Label>
Also I have set
this.DataContext = new MainViewModel();
in MainView.cs
What am I missing?
答案1
得分: 2
你需要在某处初始化Student
属性:
class MainViewModel : ViewModelBase
{
private Student _student = new Student(); //<--
public Student Student
{
get { return _student; }
set
{
if (_student != value)
{
_student = value;
OnPropertyChanged(nameof(Student));
}
}
}
}
此外,请注意,在`MainViewModel`类中应使用`nameof`运算符来引发`PropertyChanged`事件以更新*属性*。
英文:
You need to initialize the Student
property somewhere:
class MainViewModel : ViewModelBase
{
private Student _student = new Student(); //<--
public Student Student
{
get { return _student; }
set
{
if (_student != value)
{
_student = value;
OnPropertyChanged(nameof(Student));
}
}
}
}
Also note that you should use the nameof
operator to raise the PropertyChanged
event for the property in the MainViewModel
class.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论