1

我一直在学习本教程并将我的 Datagrid 成功绑定到 XML 数据提供程序资源。

当 xmlfile(xmldataprovider 被引用)更改时,我的网格没有更新。

所以我遵循了这个人的教程,虽然每次文件更改时我都会收到通知(本教程提供了一个自定义类“myxmldataprovider”,它扩展了 xmldataprovider 并有一个文件系统观察程序监听文件更改。类中有一个名为“ on file changed”,并在 XML 文件更改时访问)。正如第二个教程所建议的那样,在文件更改功能中使用刷新没有做任何事情来更新数据网格或数据提供者的内容。

我的项目真的迟到了……这似乎是唯一让我无法继续前进的事情。我搜索了互联网并浏览了无数的论坛。并且还没有找到一个有效的明确答案。

自定义类

public class MyXmlDataProvider: XmlDataProvider
{

    public new Uri Source
    {
        get { return base.Source; }
        set
        {
base.Source = value;
            FileSystemWatcher watcher = new FileSystemWatcher();
            //set the path of the XML file appropriately as per your requirements
            watcher.Path = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\..\\"));
            //name of the file i am watching
            watcher.Filter = value.OriginalString;

            //watch for file changed events so that we can refresh the data provider
            watcher.Changed += new FileSystemEventHandler(file_Changed);


            //finally, don't forget to enable watching, else the events won't fire           
            watcher.EnableRaisingEvents = true;
        }
    }

    void file_Changed(object sender, FileSystemEventArgs e)
    {base.refresh();

}

xml

<local:MyXmlDataProvider Source="XMLFile123.xml"
                     XPath="firstnode" x:Key="xml" />
</Window.Resources>
<DataGrid Name="CustomerGrid" AutoGenerateColumns="False"
              ItemsSource="{Binding Source={StaticResource xml},XPath=*}">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding XPath=@attribute1}"
                                Header="attribute1" />
            <DataGridTextColumn Binding="{Binding XPath=@attribute2}"
                                Header="attribute2" />
            <DataGridTextColumn Binding="{Binding XPath=@attribute3}"
                                Header="attribute3" />
            <DataGridTextColumn Binding="{Binding XPath=@attribute4"
                                Header="attribute4" />
        </DataGrid.Columns>
    </DataGrid>
4

0 回答 0