[英]Set the valuer of selected combobox item in c# windows universal
這是我的組合框
<ComboBox
Name="truck_trypes_combo"
DisplayMemberPath="description"
SelectedValuePath="id"
Header="Truck category"
>
我正在通過設置其itemsource
TruckTypesSqlite truckypessqlite = new TruckTypesSqlite();
truck_trypes_combo.ItemsSource = truckypessqlite.GetAllTruckTypes();
在我的TruckTypesqlite中
class TruckTypesSqlite {
public List<TruckTypesModel> GetAllTruckTypes()
{
//fetch data from sqlite and return a list of type TruckTypesModel
}
}
TruckTypesModel
類包含一個id和description屬性。
上面的作品,但現在我該如何設置組合框的所選項目,假設我的ID為25
經過一些研究,我發現我需要將SelectedIndex
設置為c#的新值,如何在GetAllTruckTypes()返回的列表中獲取類似於25的值的索引,以便我可以簡單地執行
public void setSeletedValue(){
//set the index of id value 25
truck_trypes_combo.SelectedIndex = ;//index of id value 25
}
嘗試這個:
public void setSeletedValue(int id)
{
var allTruckTypes = truckypessqlite.GetAllTruckTypes();
int index = allTruckTypes.FindIndex(t => t.id == id);
if (index != -1)
{
truck_trypes_combo.SelectedIndex = index;
}
}
您可能還需要通過將allTruckTypes
為公共屬性來改進代碼,以便可以在多種方法中重用它,並且還對組合框的SelectedItem
使用數據綁定,而不是顯式設置其SelectedIndex。
但是,由於您剛剛開始使用C#,因此,我僅向您展示如何從列表中查找項目(及其索引)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.