我一直关注此tutorial并将我的Datagrid成功绑定到XML数据提供程序资源。
当xmlfile(引用xmldataprovider)发生变化时,我的网格没有更新。
所以我跟着这个人的tutorial,每当文件发生变化时我都会收到通知(教程提供了一个自定义类'myxmldataprovider',它扩展了xmldataprovider并且有一个文件系统观察者监听文件更改。类中的一个函数,名为“on file changed”,并在更改XML文件时访问它。在第二个教程中建议使用文件更改函数中的刷新没有做任何事情来更新数据网格或数据提供者的内容。
我的项目真的很晚......这似乎是阻止我继续前进的唯一因素。我搜索了互联网并浏览了无数的论坛。并且尚未找到有效的明确答案。
自定义类
public class MyXmlDataProvider: XmlDataProvider
{
public new Uri Source
{
get { return base.Source; }
set
{
base.Source = value;
FileSystemWatcher watcher = new FileSystemWatcher();
//set the path of the XML file appropriately as per your requirements
watcher.Path = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\..\\"));
//name of the file i am watching
watcher.Filter = value.OriginalString;
//watch for file changed events so that we can refresh the data provider
watcher.Changed += new FileSystemEventHandler(file_Changed);
//finally, don't forget to enable watching, else the events won't fire
watcher.EnableRaisingEvents = true;
}
}
void file_Changed(object sender, FileSystemEventArgs e)
{base.refresh();
}
XAML
<local:MyXmlDataProvider Source="XMLFile123.xml"
XPath="firstnode" x:Key="xml" />
</Window.Resources>
<DataGrid Name="CustomerGrid" AutoGenerateColumns="False"
ItemsSource="{Binding Source={StaticResource xml},XPath=*}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding XPath=@attribute1}"
Header="attribute1" />
<DataGridTextColumn Binding="{Binding XPath=@attribute2}"
Header="attribute2" />
<DataGridTextColumn Binding="{Binding XPath=@attribute3}"
Header="attribute3" />
<DataGridTextColumn Binding="{Binding XPath=@attribute4"
Header="attribute4" />
</DataGrid.Columns>
</DataGrid>