如何设置ComBox的默认值,即绑定Combox的数据源?
Xaml文件里:
<ComboBox ItemsSource="{Binding DisplayItems,Mode=TwoWay}"
SelectedItem="{Binding SelectedDisplayItem,Mode=TwoWay}"/>
<Label Content="{Binding SelectedDisplayItem, Mode=TwoWay}"/>
cs文件里:
public partial class MainWindow : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
List<string> items = new List<string>();
items.Add("MRB");
items.Add("UAI");
items.Add("Scrap");
DisplayItems = items;
}
private List<string> _displayItems;
public List<string> DisplayItems
{
get { return _displayItems; }
set
{
_displayItems = value;
NotifyPropertyChanged("DisplayItems");
}
}
private string _selectedDisplayItem;
public string SelectedDisplayItem
{
get { return _selectedDisplayItem; }
set
{
_selectedDisplayItem = value;
NotifyPropertyChanged("SelectedDisplayItem");
}
}
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
this.cmbuserType.ValueMember = ds.Tables[0].Columns[0].ColumnName.ToString();
this.cmbuserType.DisplayMember = ds.Tables[0].Columns[1].ColumnName.ToString();
加上:
comboBox.SelectedValue="默认值"; //默认值是属于this.cmbuserType.ValueMember里的值。
'<items LineId="38" LineName="穗港线" />'+
'<items LineId="39" LineName="穗港线" />'+
'<items LineId="40" LineName="阿萨德" />'+
'<items LineId="58" LineName="qq" />'+
'<items LineId="60" LineName="AAAA" />'+
'<items LineId="66" LineName="111" />'+
'<items LineId="67" LineName="11" />'+
'<items LineId="68" LineName="1234" />'+
'<items LineId="70" LineName="1234eee" />'+
'</data>';
var xml:XML=new XML(str);
var nameArrC:ArrayCollection=new ArrayCollection();
var objOne:Object=new Object();
objOne.id="-1";
objOne.name="所有线路";
nameArrC.addItem(objOne);
for each(var x:XML in xml.items){
var objs:Object=new Object();
objs.id=x.@LineId;
objs.name=x.@LineName;
nameArrC.addItem(objs);
}
paln.lineName.dataProvider=nameArrC;
paln.lineName.labelField="name";
paln.lineName.selectedIndex=0;
lineId="-1";
获取结果可以是这样的:paln.lineName.selectedItem.name;