我現在對組合框有點沮喪,並且希望有人對我的問題有一個答案。問題出在SelectedItem上。當我在調試器中運行我的應用程序時,如果我在項目中輸入與項目(即.. a,b或c)匹配的組合框中的文本,然後刪除文本,它將引發空引用異常。如果我在ComboBox中輸入文本並且與項目中的項目(即.. z)不匹配,然後刪除文本,則不會崩潰。這種行爲只發生在調試器中。如果我在外面運行應用程序,我不會崩潰。我正在使用mvvmlight grabit,但我並不認爲它與此有關。我的代碼如下Combobox SelectedItem DataBinding NullReference異常
查看:
<ComboBox IsEditable="True"
VerticalAlignment="Top"
ItemsSource="{Binding Items}"
DisplayMemberPath="Name"
SelectedItem="{Binding Item,Mode=TwoWay}"/>
型號:
public class Item
{
public string Name { get; set; }
public int Id { get; set; }
}
VM:
public MainViewModel()
{
Items = new List<Item>
{
new Item {Name="a", Id=0},
new Item {Name="b", Id=1},
new Item {Name="c", Id=2},
};
}
/// <summary>
/// The <see cref="Items" /> property's name.
/// </summary>
public const string ItemsPropertyName = "Items";
private List<Item> _items;
/// <summary>
/// Sets and gets the Items property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public List<Item> Items
{
get
{
return _items;
}
set
{
Set(ItemsPropertyName, ref _items, value);
}
}
/// <summary>
/// The <see cref="Item" /> property's name.
/// </summary>
public const string ItemPropertyName = "Item";
private Item _item;
/// <summary>
/// Sets and gets the Item property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public Item Item
{
get
{
return _item;
}
set
{
Set(ItemPropertyName, ref _item, value);
}
}
當你說你正在輸入和刪除項目時,你能解釋多一點你指的是什麼嗎?這是在用戶界面?或者在代碼中?要麼...? – Tim
當我在調試器中運行應用程序時,ComboBox屬性IsEditable =「True」。因此,我可以添加和刪除組合框中的文本。對不起,我會編輯以清楚說明。 – poco
乍一看,你的代碼看起來很完美,應該一次運行。所以我試了一下,它按預期工作。所以你提供的代碼沒有問題。 – Nitesh