zoukankan      html  css  js  c++  java
  • ComboBox、ListBox绑定和获取数据 no

    绑定主要是通过设置静态数据源,然后设置绑定控件的DisplayMemberPath和SelectedValuePath

    界面代码:

    View Code
    xmlns:c="clr-namespace:WPF1" >
    <Page.Resources>
    <c:EmPAll x:Key="empAll"></c:EmPAll>
    <c:AllData x:Key="allData"></c:AllData>
    </Page.Resources>
    <Grid>
    <ComboBox Height="23" ItemsSource="{ StaticResource empAll}" DisplayMemberPath="Name" SelectedValuePath="ID" HorizontalAlignment="Left" Margin="47,37,0,0" Name="comboBox1" VerticalAlignment="Top" Width="120"/>
    <ListBox Height="60" ItemsSource="{ StaticResource allData}" DisplayMemberPath="Name" SelectedValuePath="ID" HorizontalAlignment="Left" Margin="48,133,0,0" Name="listBox1" VerticalAlignment="Top" Width="167"/>
    <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="197,25,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click"/>

    </Grid>


    后台代码:

    View Code
    namespace WPF1
    {
    ///<summary>
    /// 绑定Combox.xaml 的交互逻辑
    ///</summary>
    public partial class 绑定Combox : Page
    {
    public 绑定Combox()
    {
    InitializeComponent();
    }

    //获取选中的值
    private void button1_Click(object sender, RoutedEventArgs e)
    {
    string val = comboBox1.SelectedValue.ToString();
    var val2 = (listBox1.SelectedItem as Emp).Name;
    MessageBox.Show(val + "," + val2);
    }
    }

    public class Emp
    {
    public int ID { get; set; }
    public string Name { get; set; }
    }

    public class EmPAll : System.Collections.ObjectModel.ObservableCollection<Emp>
    {
    public EmPAll()
    {
    this.Add(new Emp { ID = 1, Name = "A" });
    this.Add(new Emp { ID = 2, Name = "B" });
    }
    }

    public class AllData : System.Collections.ObjectModel.ObservableCollection<Emp>
    {
    public AllData()
    {
    for (int i = 0; i < 10; i++)
    {
    this.Add(new Emp { ID = i, Name = "Name" + i });
    }
    }
    }
    }
  • 相关阅读:
    二维数组
    数组经典排序
    数组复制方法
    循环
    方法和包
    switch

    注释
    面向对象优点
    有参
  • 原文地址:https://www.cnblogs.com/252e/p/2242039.html
Copyright © 2011-2022 走看看