开发者

C# WPF: Display child nodes of selected parent node as a grid

I hav开发者_如何转开发e a xml like this:

<root>
<project name="p1">
 <row field1="31" field2="3" Name="Joe"/>
  <row field1="39" field2="3" Name="Joey"/>
  <row field1="37" field2="3" Name="Joei"/>
</project>
<project name="p2">
 <row field1="31" field2="3" Name="Joe"/>
  <row field1="39" field2="3" Name="Joey"/>
</project>
</root>

Now the listbox displays the projects. When a project is selected in listbox, a grid has to display the rows. Is it possible to do this in Xaml? Or should i do it in the code as part of listbox's selectionChanged Event?


Yes. Just name your ListBox, bind the DataGrid's DataContext property to the ListBox's SelectedItem property, then set the ItemsSource of the DataGrid to the corresponding xml node.

See the code below. It uses a ListView, though, instead of a DataGrid.

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <XmlDataProvider x:Key="data">
        <x:XData>
            <root xmlns="">
                <project name="p1">
                    <row field1="31" field2="3" Name="Joe"/>
                    <row field1="39" field2="3" Name="Joey"/>
                    <row field1="37" field2="3" Name="Joei"/>
                </project>
                <project name="p2">
                    <row field1="31" field2="3" Name="Joe"/>
                    <row field1="39" field2="3" Name="Joey"/>
                </project>
            </root>
        </x:XData>
    </XmlDataProvider>
</Window.Resources>
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="1*"/>
        <ColumnDefinition Width="3*"/>
    </Grid.ColumnDefinitions>

    <ListBox x:Name="listBox" ItemsSource="{Binding Source={StaticResource data}, XPath=root/project}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding XPath=@name}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

    <ListView Grid.Column="1" DataContext="{Binding ElementName=listBox, Path=SelectedItem}" ItemsSource="{Binding XPath=row}">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Field1" DisplayMemberBinding="{Binding XPath=@field1}"/>
                <GridViewColumn Header="Field2" DisplayMemberBinding="{Binding XPath=@field2}"/>
                <GridViewColumn Header="Field3" DisplayMemberBinding="{Binding XPath=@Name}"/>
            </GridView>
        </ListView.View>
    </ListView>
</Grid>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜