像INotifyCollectionChanged火灾的xml文件改变
-
22-09-2019 - |
题
这是可能的实现INotifyCollectionChanged或其它接口等的IObservable以使得能够结合来自该文件的XML文件滤波的数据改变?我看到与文件的更改属性或收藏,但什么例子?
我有代码来过滤和绑定的XML数据给列表框:
XmlDocument channelsDoc = new XmlDocument();
channelsDoc.Load("RssChannels.xml");
XmlNodeList channelsList = channelsDoc.GetElementsByTagName("channel");
this.RssChannelsListBox.DataContext = channelsList;
解决方案
尝试使用FileSystemWatcher的
private static void StartMonitoring()
{
//Watch the current directory for changes to the file RssChannels.xml
var fileSystemWatcher = new FileSystemWatcher(@".\","RssChannels.xml");
//What should happen when the file is changed
fileSystemWatcher.Changed += fileSystemWatcher_Changed;
//Start watching
fileSystemWatcher.EnableRaisingEvents = true;
}
static void fileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
{
Debug.WriteLine(e.FullPath + " changed");
}
其他提示
您将必须实现INotifyCollectionChanged你自己,看文件系统变化System.IO使用FileSystemWatcher类
在XmlDocument
已经引发NodeChanged
事件。如果您使用的XmlDataProvider
作为绑定源,它监听NodeChanged
事件和刷新绑定。如果你改变它的Document
性能也刷新绑定。再加上与FileSystemWatcher
,你对你的方式。
一个简单的例子:
<Window x:Class="WpfApplication18.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<XmlDataProvider x:Key="Data" XPath="/Data">
<x:XData>
<Data xmlns="">
<Channel>foo</Channel>
<Channel>bar</Channel>
<Channel>baz</Channel>
<Channel>bat</Channel>
</Data>
</x:XData>
</XmlDataProvider>
</Window.Resources>
<StackPanel Margin="50">
<ListBox ItemsSource="{Binding Source={StaticResource Data}, XPath=Channel}" />
<Button Margin="10"
Click="ReloadButton_Click">Reload</Button>
<Button Margin="10"
Click="UpdateButton_Click">Update</Button>
</StackPanel>
</Window>
在事件处理程序:
private void ReloadButton_Click(object sender, RoutedEventArgs e)
{
XmlDocument d = new XmlDocument();
d.LoadXml(@"<Data xmlns=''><Channel>foobar</Channel><Channel>quux</Channel></Data>");
XmlDataProvider p = Resources["Data"] as XmlDataProvider;
p.Document = d;
}
private void UpdateButton_Click(object sender, RoutedEventArgs e)
{
XmlDataProvider p = Resources["Data"] as XmlDataProvider;
XmlDocument d = p.Document;
foreach (XmlElement elm in d.SelectNodes("/Data/Channel"))
{
elm.InnerText = "Updated";
}
}
不隶属于 StackOverflow