根据XML
文件定义 ComboBox ItemsSource
,有人可以解释并更正以下XAML吗?
XAML:
<ComboBox Name="cbConnection" DataContext="{Binding Source=c:\temp\ConnectionList.xml, XPath=DBConnection}" ItemsSource="{Binding XPath=ComboItem}" DisplayMemberPath="Key" SelectedValuePath="Value">
c:\ temp \ ConnectionList.xml:
<?xml version="1.0" encoding="utf-8" ?>
<DBConnection>
<ComboItem>
<Key>Computer-A</Key>
<Value>Server=COMPA;Database=MyDB;Integrated Security=SSPI;</Value>
</ComboItem>
<ComboItem>
<Key>Computer-B</Key>
<Value>Server=COMPB\SQL2012STD;Database=MyDB;Integrated Security=SSPI;</Value>
</ComboItem>
</DBConnection>
答案 0 :(得分:3)
您不一定需要使用DataContext。只需适当设置ItemsSource即可。
这是XMLDataProvider,将其放在页面的资源字典中:
<XmlDataProvider x:Key="XmlData"
Source="c:\temp\ConnectionList.xml">
</XmlDataProvider>
以下是更正的ComboBox:
<ComboBox x:Name="cbConnection"
ItemsSource="{Binding Source={StaticResource XmlData}, XPath=//ComboItem}"
DisplayMemberPath="Key"
SelectedValuePath="Value" />
以下是更正后的XML:
<?xml version="1.0" encoding="utf-8" ?>
<DBConnection>
<ComboItem>
<Key>Computer-A</Key>
<Value>Server=COMPA;Database=MyDB;Integrated Security=SSPI;</Value>
</ComboItem>
<ComboItem>
<Key>Computer-B</Key>
<Value>Server=COMPB\SQL2012STD;Database=MyDB;Integrated Security=SSPI;</Value>
</ComboItem>
</DBConnection>