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