直接粘過來一個方法。。
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方式就可以了。