qualcosa come incendi INotifyCollectionChanged su file xml modificati
-
22-09-2019 - |
Domanda
E 'possibile implementare INotifyCollectionChanged o altra interfaccia come IObservable per consentire di legare i dati filtrati dal file XML su questo file cambiato? Vedo esempi con proprietà o di raccolta, ma quello che con i file modifiche?
ho che il codice per filtrare e dati XML legano casella per elencare:
XmlDocument channelsDoc = new XmlDocument();
channelsDoc.Load("RssChannels.xml");
XmlNodeList channelsList = channelsDoc.GetElementsByTagName("channel");
this.RssChannelsListBox.DataContext = channelsList;
Soluzione
Provare a usare un 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");
}
Altri suggerimenti
Si dovrà implementare INotifyCollectionChanged da soli, a guardare per le modifiche del file system utilizzano la classe FileSystemWatcher in System.IO
Il XmlDocument
solleva già eventi NodeChanged
. Se si utilizza un XmlDataProvider
come fonte vincolante, ascolta NodeChanged
eventi e rinfresca le associazioni. Rinfresca anche le associazioni se si cambia la sua proprietà Document
. Che combinano con la FileSystemWatcher
e siete sulla buona strada.
Un semplice esempio:
<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>
I gestori di eventi:
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";
}
}