2013-04-12 83 views
0

我做了一個程序化的custon uipicker在一個動作表內,現在我需要設置一個文本字段,選中的選擇器的項目。隨着日期選擇器,我得到的價值是這樣的:Monotouch獲得UiPickerView選定項目

actionSheetDatePicker.DatePicker.ValueChanged += (s, e) => { 
       this.lblCheckOut.Text = f.ToString ((s as UIDatePicker).Date); 
      }; 

現在我試圖做同樣的事情與我UIPickerView,但我沒有方法的ValueChanged。

有沒有人可以幫助我獲得用我的選擇器選擇的項目的價值。

在此先感謝。

回答

0

UIPickerViewDelegate有一個Selected方法,您可以在用戶選擇一個值時引發事件。

+0

謝謝傑森,請您分享一些代碼。 – Jean

4

爲了詳細說明Jason的答案,下面是使用UIPickerView作爲自定義日期選擇器的代碼示例。希望它能幫助別人。

UIPickerView datePicker = new UIPickerView(); 
var mod = new DatePickerDataModel(); 
datePicker.Model = mod; 

mod.ValueChanged += (object sender, EventArgs e) => { 
    _selectedDate = mod.SelectedItem; 
}; 


class DatePickerDataModel : UIPickerViewModel 
    { 
     public event EventHandler<EventArgs> ValueChanged; 

     public List<DateTime> Items { get; private set; } 

     public DateTime SelectedItem { 
      get { return Items [selectedIndex]; } 
     } 

     int selectedIndex = 0; 

     public DatePickerDataModel() 
     { 
      var items = new List<DateTime>(); 
      for (int i = 0; i < 14; i++) { 
       items.Add (DateTime.Now.Subtract (TimeSpan.FromDays (i))); 
      } 
      Items = items; 
     } 

     public override nint GetRowsInComponent (UIPickerView picker, nint component) 
     { 
      return Items.Count; 
     } 

     public override nint GetComponentCount (UIPickerView picker) 
     { 
      return 1; 
     } 

     public override void Selected (UIPickerView picker, nint row, nint component) 
     { 
      selectedIndex = (int)row; 
      ValueChanged?.Invoke(this, EventArgs.Empty()); 
     } 

     public override string GetTitle (UIPickerView pickerView, nint row, nint component) 
     { 
      var t = Items [(int)row]; 
      var m = t.ToString ("MMM"); 
      var d = t.ToString ("ddd"); 
      return $"{d} {m} {t.Day}"; 
     } 

     public override nfloat GetRowHeight (UIPickerView picker, nint component) 
     { 
      return 44; 
     } 
    }