zoukankan      html  css  js  c++  java
  • WPF 控件之ComboBox绑定

    直接粘过来一个方法。。

    WPF中提供了数据绑定的功能,操作起来很方便,集合类的控件几乎都可以用数据源来进行数据的绑定,下面操作一下下拉列表框控件ComboBox控件的数据绑定操作。

    要绑定到ComboBox控件的自定义类:

    public class LocationRoad
    {
        public int ID { setget; }
        public string Code { setget; }
        public string Info { setget; }
    }

    建立数据源,我们就将此数据集合当作数据源绑定到ComboBox:

    ///
    /// 当ComboBox选中项更改时发生
    ///
    private LocationRoad _selectLocation;
    public LocationRoad SelectLocation
    {
        get
        {
            return this._selectLocation;
        }
        set
        {
            this._selectLocation = value;
            if (this.PropertyChanged != null)
                PropertyChanged(thisnew PropertyChangedEventArgs("SelectLocation"));
        }
    }
     
    private ObservableCollection _locationRoad = null;
     
    public ObservableCollection LocationSource
    {
        get
        {
            if (this._locationRoad == null)
            {
                this._locationRoad = new ObservableCollection() {
                     new LocationRoad() { ID = 1, Code = "NGQ", Info = "南岗区" },
                     new LocationRoad() { ID = 2, Code = "DLQ", Info = "道里区" },
                     new LocationRoad() { ID = 3, Code = "DWQ", Info = "道外区" },
                     new LocationRoad() { ID = 4, Code = "PFQ", Info = "平房区" },
                     new LocationRoad() { ID = 5, Code = "XFQ", Info = "香坊区" },
                     };
     
            }
            return this._locationRoad;
        }
        set
        {
            this._locationRoad = value;
            if (this.PropertyChanged != null)
                PropertyChanged(thisnew PropertyChangedEventArgs("LocationSource"));
        }
    }

    前台XAML文件绑定方式:

    <ComboBox Margin="-16,3,0,5" Grid.Row="1" Grid.Column="2" Grid.ColumnSpan="2" Name="cboxLocationKeyword"
     ItemsSource="{Binding LocationSource,Mode=OneWay}"   --->单项绑定数据源
     SelectedValuePath="ID"     --->这个是选中后的值,应该就是SelectedValue
     DisplayMemberPath="Info"   --->这个是显示的text
     SelectedItem="{Binding SelectLocation}" />

    如果要进行双向绑定或其他的绑定方式,只要更改上面binging块中的Mode方式就可以了。

  • 相关阅读:
    20165309 Linux安装及学习
    20165309 技能学习经验与C语言
    20165309 我期望的师生关系
    20165317-我期望的师生关系
    20165308 学习基础和C语言基础调查
    20165308 我期望的师生关系
    20165320 结对编程学习第一周
    20165320 第七周学习总结
    20165320 第六周学习总结
    20165320 实验一 java环境的熟悉
  • 原文地址:https://www.cnblogs.com/mantian/p/2871775.html
Copyright © 2011-2022 走看看