c#通过另一个项目解决方案(绑定)发送数据通知

本文关键字:数据 通知 绑定 另一个 项目 解决方案 | 更新日期: 2023-09-27 18:15:54

我有2个项目,一个包含我的模型,另一个包含我的视图(Windows窗体)。我试图刷新我的视图,特别是一个标签根据模型变化在我的构建()方法使用绑定,但没有工作。我不知道我的代码是错的还是不可能的。

编辑:实际上,似乎标签需要Update()或Refresh()调用在他的窗口中以图形方式更新…这可以解释我的问题

这是我的Model类:

// ModelBuilder : INotifyPropertyChanged 
public event PropertyChangedEventHandler PropertyChanged;
private Substation currentSubstation;
public Substation CurrentSubstation
{
   get
   {
       return this.currentSubstation;
   }
   set
   {
       if (value != this.currentSubstation)
       {
           this.currentSubstation = value;
           NotifyPropertyChanged("CurrentSubstation");
        }
    }
}
private void NotifyPropertyChanged(String propertyName)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}
 public void Build()
 {
     foreach (Uri substationUri in substationsUri)
     {                 
         Substation substation = new Substation(substationUri); // long process
         this.CurrentSubstation = substation;
     } 
 }

这是我的观点

private void StartImportation_Click(object sender, EventArgs e)
{
   this.model = new ModelBuilder(); 
   // Old mistake: 
   //this.timeLabel.DataBindings.Add(new Binding("Text", this.model.CurrentSubstation,"name")); 
   this.timeLabel.DataBindings.Add(new Binding("Text", this.model, "CurrentSubstation.name")); 
   this.model.Build(); //  I'd like to see the current substation created name
}

c#通过另一个项目解决方案(绑定)发送数据通知

原因是您绑定到初始this.model.CurrentSubstation,但是当您Build()时,ModelBuilder被分配了一个新的Substation。然而,在此过程中,旧的CurrentSubstation从未改变。

new Binding("Text", this.model.CurrentSubstation, "name")

将绑定更改为

new Binding("Text", this.model, "CurrentSubstation.name")