你可以給綁定源添加「默認」值。
假如你有一個綁定到ComboBox
public class ShippingMethod
{
public int Id { get; set; }
public string Name { get; set; }
}
然後你就可以創建ShippingMethod
與「默認」值的情況下,它每次更新值的時間添加到BindingList<ShippingMethod>
一個ShippingMethod
類。
對於是否存在給定值,檢查的使用Dictionary
如果不是 - 設置默認
private Dictionary<int, ShippingMethod> _allMethods;
private ShippingMethod _defaultShippingMethod = new ShippiingMethod
{
Id = 0, Name = "Not selected"
}
private void SetUpShippingMethods(IEnumerable<ShippingMethod> methods)
{
_allMethods = methods.ToDictionary(method => method.Id);
var shippingMethods = new List<ShippingMethod> { _defaultShippingMethod };
shippingMethods.AddRange(methods);
_comboBox.ValueMember = "Id";
_comboBox.DisplayMember = "Name";
_comboBox.DataSource= shippingMethods;
}
private void SetSelectedShippingMethod(ShippingMethod method)
{
If (method == null)
{
_comboBox.SelectedValue = _defaultMethod.Id;
return;
}
if (_allMethods.ContainsKey(method.Id))
{
_comboBox.SelectedValue = method.Id;
}
else
{
_comboBox.SelectedValue = _defaultMethod.Id;
}
}
如果使用MVVM
和具有ViewModel
,其屬性Methods
和SelectMethod
- 您可以使用相同的方法在的ViewModels,而是將它們設置直接到ComboBox
您只需返回「已處理」集合或「已處理」選定值。
如果您不想在ViewModel
中使用此代碼,則可以在視圖端的Binding.Format
事件中使用它們。
首先,實際上在源數據中很少會出現「1」值,但GUID將最常使用,儘管也會實現對其他種類的鍵的支持(在某些情況下會使用非數字字符串,數字支持可能發生在未來需要),所以機會是「1」是不會出現在源的BindingList(和組合框本身,特別是當它被綁定到它,甚至如果不是)也可以空着。這種解決方案似乎不適用於任何情況,或者我錯了嗎? – Ivan
它不會拋出任何異常 – Usman
@Ivan您可以使用「0」它將選擇空值如果值不存在 – Usman