WPF 控件之ComboBox绑定


直接粘过来一个方法。。

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

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

public  class  LocationRoad
{
     public  int  ID {  set get ; }
     public  string  Code {  set get ; }
     public  string  Info {  set get ; }
}

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

///
/// 当ComboBox选中项更改时发生
///
private  LocationRoad _selectLocation;
public  LocationRoad SelectLocation
{
     get
     {
         return  this ._selectLocation;
     }
     set
     {
         this ._selectLocation = value;
         if  ( this .PropertyChanged !=  null )
             PropertyChanged( this new  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( this new  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方式就可以了。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM