0

INotifyCollectionChangedまたはIObservableのような他のインターフェースを実装して、変更されたこのファイルのxmlファイルからフィルター処理されたデータをバインドできるようにすることは可能ですか?プロパティまたはコレクションの例が表示されますが、ファイルの変更はどうなりますか?

xmlデータをフィルタリングしてリストボックスにバインドするコードがあります。

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

3 に答える 3

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");
    }
于 2010-03-24T07:58:14.170 に答える
1

ファイルシステムの変更を監視するには、System.IOのFileSystemWatcherクラスを使用して、INotifyCollectionChangedを独自に実装する必要があります。

于 2010-03-24T03:36:13.353 に答える
1

XmlDocumentすでにイベントを発生させますNodeChangedXmlDataProviderバインディングソースとしてを使用する場合、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";
    }
}
于 2010-03-24T08:01:22.943 に答える