2010-01-12 55 views
1

我需要Listbox1的选定项目为第二个Listbox提供XmlDataprovider源。如何设置WPF父/子列表框

ListBox1中的用途:

<XmlDataProvider x:Key="CategoryXML" 
       Source="C:\Category.xml" 
       XPath="category" 
       /> 

例:Category.xml

<?xml version="1.0" encoding="ISO-8859-1"?> 

<main> 
<category> 
    <name>Local</name> 
    <XmlFileName>C:\Doc1.xml</XmlFileName> 
</category> 
<category> 
    <name>National</name> 
    <XmlFileName>C:\Doc2.xml</XmlFileName> 
</category> 
<category> 
    <name>Global</name> 
    <XmlFileName>C:\Doc3.xml</XmlFileName> 
</category> 
</main> 

XAML:

<ListBox ItemsSource="{Binding Source={StaticResource CategoryXML},XPath=//main//category}" 
     SynchronizedWithCurrentItem="True" Name="CategoryList"> 

ListBox2:

<XmlDataProvider x:Key="itemXML" 
       Source="?" **XmlFileName of select item in Listbox1** 
       XPath="item" 
       /> 

我遇到的问题是找到使XmlFileName成为itemXML源代码的正确语法。用户将选择列表框1中的<name>,并将<XmlFileName>发送到itemXML,其中feedbox列表框2

+1

提示:XML(和XAML)标签不会在正常文本中显示,因为SO会将它们视为HTML标签(并且浏览器因为无法识别它们而默默无闻地呈现它们)。使用反引号或代码(101010)按钮使它们显示出来。 – itowlson 2010-01-12 00:55:49

回答

0

我不知道你可以通过普通的数据绑定来完成。但它很容易一点点代码隐藏:

<Window x:Class="WpfApplication11.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="Master" Source="Master.xml" XPath="Master/Item"/> 
     <XmlDataProvider x:Key="Detail" XPath="Detail/Item"/> 
    </Window.Resources> 
    <StackPanel> 
     <ListBox 
      Name="MasterList" 
      ItemsSource="{Binding Source={StaticResource Master}}" 
      SelectionChanged="MasterList_SelectionChanged"> 
      <ListBox.ItemTemplate> 
       <DataTemplate> 
        <TextBox Text="{Binding XPath=Description}"/> 
       </DataTemplate> 
      </ListBox.ItemTemplate> 
     </ListBox> 
     <ListBox Name="DetailList" ItemsSource="{Binding Source={StaticResource Detail}}"> 
      <ListBox.ItemTemplate> 
       <DataTemplate> 
        <TextBlock Text="{Binding XPath=Description, Mode=TwoWay}"/> 
       </DataTemplate> 
      </ListBox.ItemTemplate> 
     </ListBox> 
    </StackPanel> 
</Window> 

然后:

private void MasterList_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    ListBox lb = sender as ListBox; 
    XmlElement elm = lb.SelectedItem as XmlElement; 
    string filename = elm.SelectSingleNode("Filename").InnerText; 
    XmlDocument d = new XmlDocument(); 
    d.Load(filename); 
    XmlDataProvider p = Resources["Detail"] as XmlDataProvider; 
    p.Document = d; 
} 

这工作,因为一个XmlDataProvider刷新,只要你设置其属性Document。你也可以从文件名中构造一个URI并设置Source属性;也刷新它。