今天意外的發現struct與class之間的一些區別。就是這些區別導致了在使用這兩個類型的資料作為ListPicker的ItemSource時的效果不一樣。
(1)使用struct類型對象作為ListPicker的ItemSource
首先定義了一個這樣一個struct結構體:
public struct MonthListPickerItem { public long Month; public bool IsLunarMonth; public MonthListPickerItem(long month, bool isLunarMonth) { Month = month; IsLunarMonth = isLunarMonth; } };
然後這樣使用它:
public partial class MonthListPicker : UserControl { #region Constants private int January = 1; private int December = 12; private int MonthsInYear = 12; #endregion #region Data Members private List<MonthListPickerItem> m_SelectedItems; #endregion #region Constructor public MonthListPicker() { InitializeComponent(); m_SelectedItems = new List<MonthListPickerItem>(); m_Era = Era.Solar; } #endregion #region Public Properties public List<MonthListPickerItem> SelectedItems { get { List<MonthListPickerItem> copy = new List<MonthListPickerItem>(); copy.AddRange(m_SelectedItems); return copy; } set { if (!m_SelectedItems.Equals(value)) { m_SelectedItems.Clear(); m_SelectedItems.AddRange(value); } } } public Era Era { get { return (Era)m_Era; } set { if (m_Era != value) { m_Era = value; NotifyEraPropertyChanged(value); } } } #endregion #region Event Handlers private void InitMonthLP() { List<MonthListPickerItem> monthsOfYear = new List<MonthListPickerItem>(); bool isLunarMonth = (Era == Era.Lunar); for (int i = January; i <= December; ++i) { monthsOfYear.Add(new MonthListPickerItem(i, isLunarMonth)); } MonthLP.ItemsSource = monthsOfYear; // 設定itemsource為12個月份 MonthLP.SelectedItems = m_SelectedItems; // 設定選中的月份 } private void NotifyEraPropertyChanged(Era era) { // do something } #endregion }
這樣的代碼運行起來時沒有問題的,ListPicker的SelectedItems會有選中效果。
(2)使用class類型對象作為ListPicker的ItemSource
但是當我將MonthListPickerItem改為class類型時,代碼沒有編譯錯誤,但是在運行時設定SelectedItems沒有效果,也就是沒有item被選中。
例如:
public class MonthListPickerItem { public long Month{get;set;} public bool IsLunarMonth{get;set;} public MonthListPickerItem(long month, bool isLunarMonth) { Month = month; IsLunarMonth = isLunarMonth; } };
這到底是什麼原因呢?
struct對象是在棧上建立的,而class對象則是在堆上建立的。在堆上建立的對象在資料區塊索引和地址空間方面會不一樣,即使儲存的內容一樣;程式在設定選中項的時候,估計是這些方面做了判斷,只要是class類型對象使用了new,實際上它們就永遠不相等,因此也就是找不到要預設選中的選項。
因此會出現這樣的選中項設定無效的情況吧。
------------------------------------------------------------------------------------------------------
但目前沒有深究這些問題,實際情況是不是上面所說的這樣也不能保證,先作為一個筆記吧,有時間再來確定一下。