WPF: ListBox绑定xml数据

前端之家收集整理的这篇文章主要介绍了WPF: ListBox绑定xml数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

继承自IEnumerable接口的各种集合都可以作为ListBox控件的数据源。WPF中的XmlDataProvider 提供了一种将xml文件作为集合数据源的便捷方式,只要所定义的xml格式正确没有拼写错误,XPath路径指定正确都可以绑定成功。 下面定义一个xml资源:

  • 定义资源并应用到ListBox
<Window
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="800" Height="500" 
  WindowStartupLocation="CenterScreen" Title="ListBox-绑定xml" SizeToContent="WidthAndHeight">
  <Window.Resources>
     <XmlDataProvider x:Key="MyXmlData" XPath="Root/Sub">
            <x:XData>
                <Root xmlns="" Name="Supermarket">
                    <Sub SubId="0" SubName="Sub0"/>
                    <Sub SubId="1" SubName="Sub1"/>
                    <Sub SubId="2" SubName="Sub2"/>
                    <Sub SubId="3" SubName="Sub3"/>
                    <Sub SubId="4" SubName="Sub4"/>
                    <Sub SubId="5" SubName="Sub5"/>
                </Root>
            </x:XData>
        </XmlDataProvider> 
  </Window.Resources>

注意这里的XPath只定义到二级的Sub,如果有多级向后追加即可。定义ListBox之前,首先介绍2个绑定属性
  1. DisplayMemberPath 用来设置显示的对象属性路径。
  2. SelectedValuePath 用来设置选择值的对象属性路径。
上边2属性的绑定方式为 @加对应的节点属性名称,这里指的是SubName与SubId。 ListBox定义如下:
      <ListBox Name="lbxml"   Width="300" Height="300" SelectionMode="Single" 
      DisplayMemberPath="@SubName" SelectedValuePath="@SubId" 
      ItemsSource="{Binding Source={StaticResource MyXmlData}}">
      <ListBox.ItemContainerStyle>
        <Style TargetType="{x:Type ListBoxItem}">
            <Setter Property="Focusable" Value="True"/>
            <Setter Property="Template">
               <Setter.Value>
                  <ControlTemplate  TargetType="{x:Type ListBoxItem}">
                       <Border x:Name="border" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="transparent">
                         <ContentPresenter SnapsToDevicePixels="True"></ContentPresenter>
                       </Border>
                       <ControlTemplate.Triggers>
                         <Trigger Property="IsSelected" Value="True">
                           <Setter Property="Background" TargetName="border" Value="#958679"></Setter>
                         </Trigger>
                       </ControlTemplate.Triggers>
                  </ControlTemplate>
               </Setter.Value>
            </Setter>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>
ContentPresenter 用来默认显示内容,也可使用其它内容控件Textblock代替。效果
列表中显示的就是DisplayMemberPath 定义的SubName。
  • 显示 选择的文本及值
ListBox的SelectedItem属性表示选择项对象,SelectedValue 属性表示选择项的值。
<UniformGrid Columns="2" Margin="2">
<TextBlock Text="{Binding SelectedItem.Attributes[SubName].Value,ElementName=lbxml,StringFormat='显示的SubName:{0}'}"></TextBlock>
<TextBlock Text="{Binding SelectedValue,StringFormat='选择的SubId:{0}'}"></TextBlock>
</UniformGrid>
整体运行效果
原文链接:https://www.f2er.com/xml/294239.html

猜你在找的XML相关文章