CSharp - 数据网格没有使用ObservableCollection更新

  显示原文与译文双语对照的内容
0 0

我已经实现了一个 DataGrid,如下所示:


<DataGrid Name="grdSignals" Grid.Column="1" ItemsSource="{Binding}" AutoGenerateColumns="False">
 <DataGrid.Columns>
 <DataGridTextColumn Header="Signal Name" Binding="{Binding SignalName}"/>
 <DataGridTextColumn Header="Value" Binding="{Binding SignalValue}"/>
 </DataGrid.Columns>
</DataGrid>

下面是我实现 ObservableCollection 中使用的属性的Class:


namespace Test
{
 public partial class MyMain : UserControl
 { 
 public ObservableCollection<Signals> ocSignalNames;
 Signals time, mode;

 public MyMain()
 {
 InitializeComponent(); 
 ocSignalNames = new ObservableCollection<Signals>(); 
 time = new Signals() { SignalName ="Time", SignalValue ="" };
 mode = new Signals() { SignalName ="Mode", SignalValue ="" };
 ocSignalNames.Add(time);
 ocSignalNames.Add(mode);
 grdSignals.DataContext = ocSignalNames;
 }
 }

 public class Signals : INotifyPropertyChanged
 {
 string _signalName, _signalValue;
 public string SignalName
 {
 get
 {
 return _signalName;
 }
 set
 {
 _signalName = value;
 }
 }

 public string SignalValue
 {
 get
 {
 return _signalValue;
 }
 set
 {
 _signalValue = value;
 OnPropertyChanged(SignalValue);
 }
 }

 public event PropertyChangedEventHandler PropertyChanged;

 private void OnPropertyChanged(string propertyName)
 {
 if (PropertyChanged!= null)
 {
 PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
 }
 }
 }
}

调试之后,我发现 ocSignalNames 在它的项目更改时正在更新。 但这些变化并没有在 DataGrid 中反映出来。 我正在更新线程中的项,如下所示:


time.SignalValue = iTest1.ToString();
mode.SignalValue = iTest2.ToString();

我错过了什么?

时间: 原作者:

0 0

你缺少正确的NotifyChanged处理程序:


 public string SignalName
 {
 get
 {
 return _signalName;
 }
 set
 {
 _signalName = value;
 OnPropertyChanged("SignalName");//Added
 }
 }

 public string SignalValue
 {
 get
 {
 return _signalValue;
 }
 set
 {
 _signalValue = value;
 OnPropertyChanged("SignalValue");//NOTE: quotation marks added
 }
 }

原作者:
0 0

你必须使用下面提到的代码。


 string _signalName, _signalValue;
 public string SignalName
 {
 get
 {
 return _signalName;
 }
 set
 {
 _signalName = value;
 OnPropertyChanged("SignalName");
 }
 }

 public string SignalValue
 {
 get
 {
 return _signalValue;
 }
 set
 {
 _signalValue = value;
 OnPropertyChanged(SignalValue);
 }
 }

你的XAML看起来像


 <DataGrid Name="grdSignals" Grid.Column="1" ItemsSource="{Binding}" AutoGenerateColumns="False">
 <DataGrid.Columns>
 <DataGridTextColumn Header="Signal Name" Binding="{Binding SignalName, Mode=TwoWay}"/>
 <DataGridTextColumn Header="Value" Binding="{Binding SignalValue, Mode=TwoWay}"/>
 </DataGrid.Columns>
 </DataGrid>

O/P

enter image description here

原作者:
...