我经历了许多相同类型的问题,但无法找到正确的解决方案。我已经为我的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;
}
}
}
答案 0 :(得分: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 ...
}