首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 其他开发语言 >

WPF 多层绑定XML,该如何处理

2012-02-26 
WPF 多层绑定XMLXML文件?xml version1.0 encodingutf-8 ?ab name一 code001c cname

WPF 多层绑定XML
XML文件

<?xml version="1.0" encoding="utf-8" ?>
<a>
  <b name="一" code="001">
  <c cname="一.1" code="001001" />
  <c cname="一.2" code="001002" />
  <c cname="一.3" code="001003" />

  </b>
  <b name="二" code="002" />
  <c cname="二.1" code="002001" />
  <c cname="二.2" code="002002" />
  <c cname="二.3" code="002003" />
</a>

test.xaml

<Window x:Class="Wpf1.test2"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="test2" Height="300" Width="300">
  <Window.Resources>
  <XmlDataProvider x:Key="xmldata" Source="data/x2.xml" XPath="a/b"/>
  <DataTemplate x:Key="dataTemplate2">
  <Grid Width="300">
  <Grid.ColumnDefinitions>
  <ColumnDefinition Width="150"/>
  <ColumnDefinition Width="150"/>
  </Grid.ColumnDefinitions>
  <Grid.RowDefinitions>
  <RowDefinition></RowDefinition>
  <RowDefinition></RowDefinition>
  </Grid.RowDefinitions>
  <TextBlock Grid.Column="0" Grid.Row="0" Text="{Binding XPath=@cname}" />
  <TextBlock Grid.Column="1" Grid.Row="0" Text="{Binding XPath=@code}" />
  </Grid>
  </DataTemplate>

  <DataTemplate x:Key="dataTemplate1">
  <Grid Width="300">
  <Grid.ColumnDefinitions>
  <ColumnDefinition Width="150"/>
  <ColumnDefinition Width="150"/>
  </Grid.ColumnDefinitions>
  <Grid.RowDefinitions>
  <RowDefinition Height="15"/>
  <RowDefinition/>
  </Grid.RowDefinitions>
  <TextBlock Grid.Column="0" Grid.Row="0" Text="{Binding XPath=@name}" />
  <TextBlock Grid.Column="1" Grid.Row="0" Text="{Binding XPath=@code}" />
  <ListBox ItemsSource="{Binding}" ItemTemplate="{StaticResource dataTemplate2}"
  Grid.Column="0" Grid.Row="1" Grid.ColumnSpan="2"/>
  </Grid>
  </DataTemplate>
  </Window.Resources>
  <Grid DataContext="{Binding Source={StaticResource xmldata}}" Width="310" >
  <Grid.ColumnDefinitions>
  <ColumnDefinition Width="150"/>
  <ColumnDefinition Width="150"/>
  </Grid.ColumnDefinitions>
  <Grid.RowDefinitions>
  <RowDefinition Height="15"/>
  <RowDefinition/>
  </Grid.RowDefinitions>



  <!--<Label>My Soccer Leagues</Label>-->
  <TextBlock Grid.Column="0" Grid.Row="0" Text="名称" />
  <TextBlock Grid.Column="1" Grid.Row="0" Text="code" />
 
  <DataGrid ItemsSource="{Binding}" Grid.Column="0" Grid.Row="1" Grid.ColumnSpan="2">
  <DataGrid.Columns>
  <DataGridTextColumn Header="名称" HeaderTemplate="{StaticResource dataTemplate1}" />
  </DataGrid.Columns>
  </DataGrid>
  </Grid>
</Window>

为什么绑定只显示<b name="一" code="001">的子集, <b name="二"/>的不显示?
请高手指教


[解决办法]
试一试这样,修改xpath

<XmlDataProvider x:Key="xmldata" Source="data/x2.xml" XPath="a/b"/>
-->
<XmlDataProvider x:Key="xmldata" Source="data/x2.xml" XPath="a"/>



<TextBlock Grid.Column="0" Grid.Row="0" Text="{Binding XPath=@name}" />
-->
<TextBlock Grid.Column="1" Grid.Row="0" Text="{Binding XPath=b/@code}" />

热点排行