[英]ComboBox and ComboBoxItem names are null
我有一個消息列表,該列表由ComboBox中的所選選項(時間,名稱或組ID)排序。 我在我的xaml中添加了一個帶有Items的ComboBox:
<ComboBox x:Name="sort_dropdown" HorizontalAlignment="Left" Margin="828,219,0,0" VerticalAlignment="Top" Width="120" SelectedIndex="0">
<ComboBoxItem x:Name="time_sort" Content="Time" Selected="time_sort_Selected"/>
<ComboBoxItem x:Name="nickname_sort" Content="Nickname" Selected="nickname_sort_Selected"/>
<ComboBoxItem x:Name="groupId_sort" Content="Group ID" Selected="groupId_sort_Selected"/>
</ComboBox>
為了使列表重新排序,我在cs文件中編寫了一個函數:
private void reorder()
{
if (time_sort.IsSelected)
fill_chat(MessageSorting.DateSort(Globals.MSG_LOCAL_LIST, ascendingOrder));
else if (nickname_sort.IsSelected)
fill_chat(MessageSorting.UserNameSort(Globals.MSG_LOCAL_LIST, ascendingOrder));
else fill_chat(MessageSorting.GroupIdSort(Globals.MSG_LOCAL_LIST, ascendingOrder));
}
運行時,我得到一個NullReferenceException。 調試后,我發現對象名稱引用為null。
示例:time_sort = null。 sort_dropdown = null。 等等。
在xaml上更改屬性無濟於事,因為沒有引用來讀取這些屬性。 謝謝。
更新:這不是主窗口,在運行該窗口類的代碼之前,我注意到它在調用.show函數之前運行。 由於某種原因,其中的代碼沒有被執行就被執行。
更新2:我有以下代碼:
public MainLoggedWindow()
{
MessageBox.Show("Before initialization");
InitializeComponent();
MessageBox.Show("after initialization");
}
運行時,第一個MessageBox出現,但第二個沒有。 從以下函數中調用reorder()函數:
private void order_dropdown_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ascendingOrder = !ascendingOrder;
reorder();
}
ascendingOrder是一個布爾值,用於保存當前的排序順序。 還有一個帶有2個項目(升序或降序)的comboBox,每次用戶更改選擇時,該函數就會運行。
更新3:在調試時遵循調用堆棧顯示initializeComponent();
調用order_dropdown_SelectionChanged(...)
,后者調用reorder()
。
解決了。
縮小問題范圍: initializeComponent();
使order_dropdown_SelectionChanged(...)
運行。
說明:在xaml的ComboBox聲明中, selectedIndex
屬性的定義如下: SelectedIndex="0"
。 因此,初始化的一部分是創建ComboBox並設置selectedindex=0
,該值立即觸發order_dropdown_SelectionChanged(...)
函數。 現在,由於尚未創建ComboBox項,因此名稱引用為null,程序崩潰了。
解決方案:不要在xaml中同時定義selectedIndex
屬性和_SelectionChanged(...)
。 我個人刪除了selectedIndex
屬性,並在initializeComponent();
之后以編程方式對其進行了定義initializeComponent();
叫做。
作為InitializeComponent
一部分,它設置對order_dropdown
的選擇; 但這是在設置命名控件之前發生的。 因此,您的reorder
方法需要通過將其當前內容包裝在if(time_sort!=null)
作為確定初始化是否已完成的一種方法來if(time_sort!=null)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.