绑定的TextBox不会更新

时间:2014-02-04 19:04:51

标签: c# wpf data-binding combobox observablecollection

我有一个ComboBox绑定到一个ObservableCollection对象(有几个属性)。组合框准确显示所有对象的所需属性,我可以按预期从组合中选择任何项目。

<ComboBox Height="23" Name="comboBox1" Width="120" Margin="5" ItemsSource="{Binding Issues}" DisplayMemberPath="Issue" SelectedValuePath="Issue" SelectedValue="{Binding Path=Issues}" IsEditable="False" SelectionChanged="comboBox1_SelectionChanged" LostFocus="comboBox1_LostFocus" KeyUp="comboBox1_KeyUp" Loaded="comboBox1_Loaded" DropDownClosed="comboBox1_DropDownClosed" IsSynchronizedWithCurrentItem="True" />

我有一系列文本框,可以显示所选对象的其他属性。这也很好。

<TextBox Height="23" Name="textBox5" Width="59" IsReadOnly="True" Text="{Binding Issues/LastSale, StringFormat={}{0:N4}}" />
<TextBox Height="23" Name="textBox9" Width="90" IsReadOnly="True" Text="{Binding Path=Issues/LastUpdate, Converter={StaticResource TimeConverter}}" />

但是...... ObservableCollection的属性定期在Code-Behind中更新,我通过在每次更新属性时添加或删除虚拟对象来更改OC。 (我发现这比其他解决方案简单。)

但是...... TextBoxes中的数据不会改变! :-(如果我从ComboBox中选择一个不同的对象,我会得到更新的信息,但是当OC被更改时它不会改变。

OC由一堆这些对象组成:

public class IssuesItems
{
  public String Issue { get; set; }
  public Double LastSale { get; set; }
  public DateTime LastUpdate { get; set; }
  ...
 }

OC被定义为:

public ObservableCollection<IssuesItems> Issues { get; set; }

并实例化:

this.Issues = new ObservableCollection<IssuesItems>();

我做错了什么?我读到的所有内容都表明,当OC中的LastSale和LastUpdate属性发生变化时(我会采取措施强制更新OC),文本框中的数据应该会改变。

1 个答案:

答案 0 :(得分:1)

ObservableCollection实现INotifyCollectionChanged允许GUI在集合中添加或删除任何项目时刷新(您无需担心手动执行此操作)。

但正如我所提到的,这仅限于添加/删除集合中的项目,但如果您希望在任何底层属性发生更改时刷新GUI,则您的基础源类必须实现INotifyPropertyChanged 向GUI发出属性已更改的通知,以便自己刷新。

IssuesItems应该在你的情况下实现INPC接口。

请参阅此内容 - How to implement INotifyPropertyChanged on class

  public class IssuesItems : INotifyPropertyChanged
  {
      private string issue;
      public string Issue
      {
          get { return issue; }
          set
          {
              if(issue != value)
              {
                 issue= value;
                 // Call OnPropertyChanged whenever the property is updated
                 OnPropertyChanged("Issue");
              }
          }
      }

      // Declare the event 
      public event PropertyChangedEventHandler PropertyChanged;
      // Create the OnPropertyChanged method to raise the event 
      protected void OnPropertyChanged(string name)
      {
          PropertyChangedEventHandler handler = PropertyChanged;
          if (handler != null)
          {
              handler(this, new PropertyChangedEventArgs(name));
          }
      }
  }

如上所述,实现与Issue类似的其他属性。

相关问题