3

我经历了许多相同类型的问题,但无法找到正确的解决方案。我已经INotifyPropertyChanged为我的MainViewModel.cs班级实现了,以查看当我的源代码更改时我的 UI 是否更新,但是当我运行我的应用程序时没有任何效果。

这是我的 Xaml 代码:

<Window.DataContext>
<ViewModel:MainViewModel/>
</Window.DataContext>
 <Grid>
   <DataGrid ItemsSource="{Binding Path=SystemStatusData,Mode=OneWay,UpdateSourceTrigger=PropertyChanged,NotifyOnTargetUpdated=True}" 
AutoGenerateColumns="False" Height="287" HorizontalAlignment="Left" Margin="12,12,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="479" >

我的 MainViewModel.cs 类:

namespace MVVM_DemoAppl.ViewModels
{
public class MainViewModel : INotifyPropertyChanged
{
  Model _myModel = new Model();
  private ObservableCollection<SystemStatus> _systemStatusData= new ObservableCollection<SystemStatus>();
  public ObservableCollection<SystemStatus> SystemStatusData
  {
    get { return _systemStatusData; }
    set
      {
        _systemStatusData= value;
        OnPropertyChanged("SystemStatusData");
      }
  }

public MainViewModel()
 {
   initializeload();
 }

private void initializeload()
{
   DataTable table = _myModel.getData();

   for (int i = 0; i < table.Rows.Count; ++i)
   SystemStatusData.Add(new SystemStatus
   {
   Systems= table.Rows[i][0].ToString(),
   Date =Convert.ToDateTime(table.Rows[i][1]),
   Types = table.Rows[i][2].ToString(),
   Messages = table.Rows[i][3].ToString()       
   Critical = Convert.ToBoolean(table.Rows[i][1]),
   });
   }

  public event PropertyChangedEventHandler PropertyChanged;

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

public class Model
{
 string con = ConfigurationManager.AppSettings["ConnectionStrings"];
 public DataTable getData()
 {
 DataTable ndt = new DataTable();
 SqlConnection sqlcon = new SqlConnection(con);
 sqlcon.Open();
 SqlDataAdapter da = new SqlDataAdapter("select * from test_DB.dbo.SystemStatus",con);
 da.Fill(ndt);
 return ndt;
 }
 }
}
4

1 回答 1

2

首次运行查询后,SQL Server 不会自动更新您的结果集。实现您所追求的最基本方法是轮询服务器以按设定的时间间隔检查更改并从那里更新屏幕。

您可以查看CDC,这将有助于确定发生了什么变化。但这些都不是自动的,您每次都需要重新运行查询。

计时器如何工作的示例:

// Background timer used to refresh...
private DispatcherTimer _timer = null;

public MainViewModel()
{
    // Do initial load
    initializeload();

    // Start the timer to refresh every 100ms thereafter (change as required)
    _timer = new DispatcherTimer();
    _timer.Tick += Each_Tick;
    _timer.Interval = new TimeSpan(0, 0, 0, 0, 100);
    _timer.Start(); 
}

// Raised every time the timer goes off
private void Each_Tick(object o, EventArgs sender)
{
    // Refresh from database etc ...
    initializeload();

    // Anything else you need ...
}

private void initializeload()
{
    // Your existing code here ...
}
于 2013-01-15T14:18:20.987 回答