Algo como InotifyCollectionChanged Incêndios no arquivo XML alterados
-
22-09-2019 - |
Pergunta
É possível implementar o InotifyCollectionChanged ou outra interface como o IOBServable para permitir vincular dados filtrados do arquivo XML neste arquivo alterado? Vejo exemplos com propriedades ou coleta, mas o que com os arquivos muda?
Eu tenho esse código para filtrar e vincular dados XML para listar a caixa:
XmlDocument channelsDoc = new XmlDocument();
channelsDoc.Load("RssChannels.xml");
XmlNodeList channelsList = channelsDoc.GetElementsByTagName("channel");
this.RssChannelsListBox.DataContext = channelsList;
Solução
Tente usar um ARFESSYSTEMWATCHER
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");
}
Outras dicas
Você precisará implementar o InotifyCollectionChanged por conta própria, para observar as alterações do sistema de arquivos Use a classe FileSystemwatcher em System.io
o XmlDocument
já aumenta NodeChanged
eventos. Se você usar um XmlDataProvider
Como sua fonte vinculativa, ele ouve NodeChanged
eventos e refresca as ligações. Também atualiza as ligações se você mudar de Document
propriedade. Combine isso com o FileSystemWatcher
E você está a caminho.
Um exemplo simples:
<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>
Os manipuladores de eventos:
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";
}
}