zoukankan      html  css  js  c++  java
  • WPF中ListBox的绑定

    WPF中列表式控件派生自ItemsControl类,继承了ItemsSource属性。ItemsSource属性可以接收一个IEnumerable接口派生类的实例作为自己的值(所有可被迭代遍历的集合都实现了这个接口,如数组、List<T>等)。每一个 ItemsControl的派生类都有自己的条目容器,如ListBox的条目容器ListBoxItem.当我们利用Binding为一个ItemsControl设置了ItemsSource属性值,ItemsControl对象会自动迭代其中的数据元素,并为每个数据元素准备一个条目容器。
    下面的例子,为ListBox绑定了一个List<T>类型的数据源,并在编写框中显示选中的Student对象的ID。

    界面效果如下:

    XAML文件代码:

    [html] view plain copy
     
     print?
    1. <Window x:Class="_6_15.MainWindow"  
    2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
    3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
    4.         Title="MainWindow" Height="350" Width="525">  
    5.     <Grid>  
    6.         <ListBox Height="164" HorizontalAlignment="Left" Margin="12,0,0,12" Name="listBox1" VerticalAlignment="Bottom" Width="471"   
    7.                  DisplayMemberPath="Name" SelectedValuePath="ID"/>  
    8.         <TextBox Height="23" HorizontalAlignment="Left" Margin="12,61,0,0" Name="textBox1" VerticalAlignment="Top" Width="120"   
    9.                  Text="{Binding SelectedItem.ID,ElementName=listBox1}"/>  
    10.         <TextBlock Height="23" HorizontalAlignment="Left" Margin="12,32,0,0" Name="textBlock1" Text="Student ID:" VerticalAlignment="Top" />  
    11.         <TextBlock Height="23" HorizontalAlignment="Left" Margin="12,106,0,0" Name="textBlock2" Text="Student List:" VerticalAlignment="Top" />  
    12.     </Grid>  
    13. </Window>  

    这里需要说明一下的是ListBox的DisplayMemberPath属性,顾名思义,其函数是ListBox中需要显示的的绑定对象的Path,而SelectedValuePath,意思是在选中某个Item时我们可以通过ListBox的SelectedValue属性获取的值的类型,如选中了张三,则通过SelectedValue我们可以获取张三的ID。
    每一个派生自ItemsControl类的类都具有上述属性,包括ListView、ListBox、ComBox、TreeView等等。

    [csharp] view plain copy
     
     print?
      1. public partial class MainWindow : Window  
      2.     {  
      3.         public MainWindow()  
      4.         {  
      5.             InitializeComponent();  
      6.   
      7.             List<Student> stuList = new List<Student>()  
      8.             {  
      9.                 new Student(){ID=1,Name="张?三¨y"},  
      10.                  new Student(){ID=2,Name="李¤?四?"},  
      11.                   new Student(){ID=3,Name="王ª?五?"}  
      12.             };  
      13.   
      14.             this.listBox1.ItemsSource = stuList;  
      15.         }  
      16.     }  
      17.     public class Student  
      18.     {  
      19.         public int ID { get; set; }  
      20.         public string Name { get; set; }  
      21.     }  
  • 相关阅读:
    龌龊的新版weiphone。
    【爆牙游记】黄山归来不看岳-走进新时代。
    我只有两天。
    聪明的苹果——iPhone 3GS。
    今天,遗憾。
    为了忘却的纪念——写给《博客园精华集Web标准之道》
    剪我一根头发,就要做我一天女人。
    产品重构。
    8月9日和妈妈的对话。
    钻石环。
  • 原文地址:https://www.cnblogs.com/wlming/p/7760038.html
Copyright © 2011-2022 走看看