【发布时间】:2020-01-30 15:01:43
【问题描述】:
我正在尝试制作一个非常简单的应用程序来学习 DataBinding 和事件。以下代码应该在我单击按钮时更改标签内容,但实际上它会更改属性但不会更新标签。
这是主要代码:
public MainWindow()
{
InitializeComponent();
environments = new ObservableCollection<Env>();
environments.Add(new Env("env1", new ObservableCollection<Cell>()));
environments.Add(new Env("env2", new ObservableCollection<Cell>()));
foreach (Env e in environments)
{
Label label = new Label
{
Content = e.Name
};
pnlMain.Children.Add(label);
}
}
private void ChangeEnvName_Click(object sender, RoutedEventArgs e)
{
foreach (Env env in environments)
{
env.Name = "test";
}
}
这是 Env 类:
class Env : INotifyPropertyChanged
{
//membres
#region membres
private string _name;
private ObservableCollection<Cell> _cells;
#endregion
//propriétés
#region propriétés
public string Name
{
get { return this._name; }
set
{
if (this._name != value)
{
this._name = value;
this.NotifyPropertyChanged("Name");
}
}
}
public ObservableCollection<Cell> Cells
{
get { return this._cells; }
set
{
if (this._cells != value)
{
this._cells = value;
this.NotifyPropertyChanged("Cells");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
//méthodes
#region méthodes
public void NotifyPropertyChanged(string propName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
#endregion
//constructeur
#region contructeur
public Env(string name, ObservableCollection<Cell> cells)
{
_name = name;
_cells = cells;
}
#endregion
}
有什么问题?当我更新Env.Name 时,不是假设更新label.content 吗?
【问题讨论】:
-
“不是假设更新 label.content” - 不。为什么要这样做?
-
@ASh omg 我对数据绑定什么都不懂,我可能真的很笨
-
您没有任何数据绑定。这就是问题