Monotouch获取UiPickerView所选项目

时间:2013-04-12 16:35:45

标签: ios xamarin.ios uipickerview

我在动作表中创建了一个以编程方式定制的uipicker,现在我需要设置一个文本字段,其中包含选择器的选择项。使用datepicker,我得到这样的值:

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

现在我正在尝试用我的UIPickerView做同样的事情,但我没有ValueChanged方法。

是否有人可以帮助我获取使用我的选择器选择的项目的价值。

提前致谢。

2 个答案:

答案 0 :(得分:5)

详细说明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;
        }
    }

答案 1 :(得分:0)

UIPickerViewDelegate有一个Selected方法,您可以在用户选择值时使用该方法引发事件。