2010-02-26 109 views
1

有人可以帮我,为什么我的列表框是空的?绑定列表框到XmlDocument

XmlDocument的包含以下XML:

<Config> 
    <Tabs> 
    <Tab Name="Test1" /> 
    <Tab Name="Test2" /> 
    </Tabs> 
</Config> 

在我的XAML文件我曾尝试以下

<Window> 
    <Grid> 
    <ListBox DataContext="{Binding {StaticResource Data}, XPath=//Tabs}" ItemsSource="{Binding XPath=Tab/@Name}"> 
    </ListBox> 
    </Grid> 
<Window> 

我知道我没有设置绑定到name属性,但不应该”如果它正在工作,那么为每个Tab节点显示XmlDocument.XmlNode.ToString()?

我的C#构造函数代码后面:

InitializeComponent(); 
this.doc = new XmlDocument(); 
doc.LoadXml(config.document.OuterXml); 
XmlDataProvider provider = (XmlDataProvider)Resources["Data"]; 
provider.Document = doc; 
provider.Refresh(); 

随着config.document.OuterXml是含有上述的XML有效的文档。

我得到这与使用集合的程序代码的工作,但我一直想弄清楚如何直接绑定到XML。

更新:列表框空

现在没有约束力的错误,但我的列表框快到了空,我有双重检查我的XML文件,甚至做MessageBox.Show(provider.Document.OuterXML),并能确认XmlDocument确实有正确的节点。

在此先感谢

+1

我没有做任何的数据绑定到XML文档尚未...但你在你的输出窗口看看看你是否收到任何数据绑定错误? – Dave

+0

谢谢你,神iv'e现在一直在使用数据绑定数周,我总是忘记检查输出窗口。我编辑我的帖子来添加我的错误,而我仍然试图解决这个问题。 –

回答

4

如果设置了XmlDataProviderDocument属性为您XmlDocument,这将刷新绑定XmlNode.NodeChanged事件引发的任何时间。由于Document不是依赖项属性,因此您不能绑定到它,因此您必须将其设置为代码;这应该做的伎俩:

在您的XAML:

<Window.Resources> 
    <XmlDataProvider x:Key="Data"/> 
</Window.Resources> 

... 

<ListBox 
    DataContext="{Binding {StaticResource Data}, XPath=Config/Tabs}" 
    ItemsSource="{Binding XPath=Tab/@Name}"/> 

在窗口的构造函数:

InitializeComponent(); 
XmlDocument d = new XmlDocument(); 
d.Load("MyData.xml"); 
XmlDataProvider p = (XmlDataProvider)Resources["Data"]; 
p.Document = d; 

现在您对XmlDocument的任何更改将在ListBox反映。

编辑:

我不能告诉你,你做错了什么,但也许你就可以在比较你与下面做什么,这是一个完整的工作,以例。

Window1.xaml:

<Window x:Class="Test.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="Window1"> 
    <Window.Resources> 
     <XmlDataProvider x:Key="Data"/> 
    </Window.Resources> 
    <ListBox 
     DataContext="{Binding Source={StaticResource Data}, XPath=Config}" 
     ItemsSource="{Binding XPath=Tabs/Tab/@Name}"/>  
</Window> 

Window1.xaml.cs:

using System.Windows; 
using System.Windows.Data; 
using System.Xml; 

namespace Test 
{ 
    public partial class Window1 : Window 
    { 
     public Window1() 
     { 
      InitializeComponent(); 

      XmlDocument d = new XmlDocument(); 
      string xml = @"<Config><Tabs><Tab Name='foo'/><Tab Name='bar'/></Tabs></Config>"; 
      d.LoadXml(xml); 
      ((XmlDataProvider) Resources["Data"]).Document = d; 
     } 
    } 
} 
+0

谢谢你,我会在星期一上班,看看它是否有效:)。我猜是没有办法在XAML中执行此操作(将xmldataprovider绑定到XmlDocument? –

+1

对,因为'Document'属性不是依赖项属性,而且只能绑定到依赖项属性 –

+0

WPF是当我把DataContext =“{Binding {StaticResource Data},XPath = Config/Tabs}”并且谷歌不是来的时候,我现在变得“无法创建类型'绑定'的实例”坦克注意关于罗伯特上的依赖属性:) –