我尝试使用尽可能接近 MVVM 的数据绑定(bind),以使用数据库中的数据更新 WPF 数据网格。我想我仍然在这个概念上挣扎,在我经历过的任何例子中我都没有找到(或理解)答案。 this里有很多信息。帖子,但除非我错过了什么,否则我下面的具体问题没有得到解决。
问题: 当另一个类更新SQL数据库时如何触发PropertyChangedEventArgs?
我已经尝试了以下方法,但是,它不起作用(大概是因为我在新实例中通知)。如果我重新打开 XAML 窗口,我可以看到其他条目已添加到数据库中,只是不会自动更新。
TableView.xaml.cs
private void AddNode()
{
SQL.InsertNode(); //this fires a method to add a row to the database
ViewModel viewmodel = new ViewModel(); //this fires the messagebox in my viewmodel the the notification is raised
viewmodel.FillList(); // this doesn't seem to do anything. Cluthing at straws really
}
希望我走在正确的道路上。为了帮助回答这个问题,我在下面提供了我认为您需要的所有内容。
这是我的XAML - TableView.xaml
<DataGrid Grid.Row="2"
x:Name="NodeTableDataGrid"
ItemsSource="{Binding Nodes, Mode=TwoWay}"
Grid.ColumnSpan ="3"
CanUserAddRows="False"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Add Row" IsReadOnly="True" Visibility="Visible"/>
<DataGridTextColumn Header="Id" Binding="{Binding Path='id'}" IsReadOnly="True" Visibility="Visible"/>
<DataGridTextColumn Header="Node Name" Binding="{Binding Path='NodeName', Mode=TwoWay}" IsReadOnly="False" />
<DataGridTextColumn Header="Easting (m)" Binding="{Binding Path='x'}" IsReadOnly="False" />
<DataGridTextColumn Header="Northing (m)" Binding="{Binding Path='y'}" IsReadOnly="False" />
<DataGridTextColumn Header="Cover Level (m)" Binding="{Binding Path='z_cover'}" IsReadOnly="False" />
</DataGrid.Columns>
</DataGrid>
这是背后的代码 - TableView.xaml.cs
public TableView()
{
InitializeComponent();
co = new ViewModel();
base.DataContext = co;
}
还有我的 View 模型
public class ViewModel : INotifyPropertyChanged
{
SQLiteCommand command;
SQLiteDataAdapter adapter;
DataSet ds;
private ObservableCollection<MyModel> _nodes;
public ObservableCollection<MyModel> Nodes
{
get
{
return this._nodes;
}
set
{
if (_nodes != value)
{
MessageBox.Show("Table changed");
OnPropertyChanged("Nodes");
}
this._nodes = value;
}
}
public ViewModel()
{
FillList();
}
public void FillList()
{
try
{
string sql = "SELECT * FROM node_table";
command = new SQLiteCommand(sql, SQL.m_dbConnection);
adapter = new SQLiteDataAdapter(command);
ds = new DataSet();
adapter.Fill(ds, "node_table");
if (Nodes == null)
Nodes = new ObservableCollection<MyModel>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
Nodes.Add(new MyModel
{
id = Convert.ToInt32(dr[0].ToString()),
NodeName = dr[1].ToString(),
x = Convert.ToInt32(dr[2].ToString()),
y = Convert.ToInt32(dr[3].ToString()),
z_cover = Convert.ToInt32(dr[4].ToString())
});
}
}
catch (Exception ex)
{
MessageBox.Show("The table view has failed to load from the database with the following error: " + ex.ToString());
}
finally
{
ds = null;
adapter.Dispose();
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
编辑捕获“来自胡安·卡洛斯·罗德里格斯”的评论
我已按如下方式修改了 TableView.xaml.cs,这确实解决了来自 View 类的更新 SQL 调用的问题,因此感谢您的回复。非常有用。
ViewModel co;
public TableView()
{
SQL.InsertNode();
InitializeComponent();
co = new ViewModel();
base.DataContext = co;
}
public void AddNode()
{
SQL.InsertNode();
co.Nodes.Clear();
co.FillList();
}
但是,我需要能够从其他类更新 SQL 数据库,因此我将遇到同样的问题。我知道这行不通,但这是我想要修复的下一个问题。
一些随机类别
public void AddNodeFromRandomClass()
{
//Updates the database succesafully, however raises the change in the wrong instance of TableView.
TableView tableView = new TableView();
tableView.AddNode();
}
最佳答案
它永远不会引发Nodes
集合,因为您没有创建ObservableCollection的新实例,而是向其中添加不会引发集合的项目。当您更改实例时,ObservableCollection
集会引发。
Nodes.Add( new MyModel()) -> "Doesn't raise the set."
ObservableCollection<MyModel> myModelOC = new ObservableCollection<MyModel>() { "Declare 3 items" };
Nodes = myModelOC -> "This will raise the set".
既然我解释了这一点(我希望我解释了自己,如果不是让我知道)我想问你几个问题。我看到这个:
public TableView()
{
InitializeComponent();
co = new ViewModel();
base.DataContext = co;
}
这是你的 xaml.cs 吗?
无论如何,我想说你的问题是你正在设置一个DataContext
,然后从另一个私有(private)方法创建一个新的VM,所以你的DataContext
的VM实例和您在私有(private)中创建的虚拟机完全不同,这就是为什么您没有更新您的DataGrid
,您正在更新未在中设置为DataContext
的虚拟机 View 。
请编辑您的帖子并指出您调用 AddNode
的位置以及如何显示 View ,以便我可以告诉您如何修复它。
首先,这并不遵循 MVVM,因为您将代码放在 View 代码隐藏中:
ViewModel co;
public TableView()
{
SQL.InsertNode();
InitializeComponent();
co = new ViewModel();
base.DataContext = co;
}
public void AddNode()
{
SQL.InsertNode();
co.Nodes.Clear();
co.FillList();
}
在执行 TableView.Show()
之前,您必须创建一个 ViewModel 并设置 TableView
DataContext
。它会是这样的:
ViewModel yourViewModel = new ViewModel();
TableView tableView = new TableView();
tableView.DataContext = yourViewModel;
tableView.Show();
您的 TableView.xaml.cs
构造函数应如下所示:
public TableView()
{
InitializeComponent();
}
你的ViewModel
构造函数应该是这样的:
public ViewModel()
{
FillList();
Nodes.Clear();// You could do this if you need it to be cleared
}
话虽如此,对于您真正的问题,我建议您使用事件。这实际上取决于您的架构是如何构建的。我将给出一个可能的方法:
创建一个新类来包含您的事件,如下所示:
public static class UpdaterEvent
{
public static event EventHandler DataUpdated;
public static void PublishDataUpdated(EventArgs args)
{
var updaterEvent = DataUpdated;
if (updaterEvent != null)
updaterEvent(null, args);
}
}
现在在您的 ViewModel 构造函数中添加以下内容:
public ViewModel()
{
FillList();
Nodes.Clear();// You could do this if you need it to be cleared
UpdaterEvent.DataUpdated += OnDataUpdated;
}
private void OnDataUpdated(object sender, EventArgs e)
{
FillList();
}
每当您需要更新数据时,只需执行以下操作:
UpdaterEvent.PublishDataUpdated(new EventArgs());
关于c# - 使用可观察对象使用数据库中的数据绑定(bind)更新数据网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52140397/