类似于INotifyCollectionChanged在xml文件上触发更改

时间:2010-03-24 02:10:55

标签: c# wpf xml inotify system.reactive

有可能实现INotifyCollectionChanged或IObservable等其他接口,以便能够从此文件上的xml文件中绑定过滤后的数据吗?我看到有关属性或集合的示例,但文件更改的内容是什么?

我有那个代码来过滤并将xml数据绑定到列表框:

XmlDocument channelsDoc = new XmlDocument();
channelsDoc.Load("RssChannels.xml");
XmlNodeList channelsList = channelsDoc.GetElementsByTagName("channel");
this.RssChannelsListBox.DataContext = channelsList;

3 个答案:

答案 0 :(得分:2)

尝试使用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");
    }

答案 1 :(得分:1)

您必须自己实现INotifyCollectionChanged,以使用System.IO中的FileSystemWatcher类来监视文件系统更改

答案 2 :(得分:1)

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";
    }
}