用于ViewController的Monotouch UIPickerView ValueChange事件

时间:2016-07-25 11:35:35

标签: c# xamarin xamarin.ios uipickerview

我希望在事件UIPickerView更改其任何组件中的值时获取事件,以便我的UIViewController可以对Labels进行更改。我只遇到PickerView模型提供的一种有用的方法:

public override void Selected(UIPickerView pickerView, nint row, nint component) 

当有任何变化时,模型中会反映出相应的变化。但是,如果我想将这些更改反映回ViewController,我应该怎么做?我想完成这项工作,就像代表 iOS 中做的那样。我对c#不太熟悉。任何帮助赞赏。感谢。

public partial class ViewController : UIViewController  
{

    public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            // Perform any additional setup after loading the view, typically from a nib.
            setupHandlers();
        }

   void setupHandlers()
        {
            pickerModel = new UnitPickerViewModel();
            pickerModel.Items = lengthArray;
            pickerModel.setDataForSecondComponent(lengthArray2);

            pickerView = new UIPickerView();
            pickerView.BackgroundColor = UIColor.LightGray;
            pickerView.DataSource = pickerModel;

        }
}

1 个答案:

答案 0 :(得分:1)

您可以创建弱而强的Obj-C样式代理:

强代表:

在您的UIPickerViewDelegate课程中创建嵌套的UIViewController课程

    class PickerDelegate : UIPickerViewDelegate
    {
        public override void Selected(UIPickerView pickerView, nint row, nint component)
        {
            base.Selected(pickerView, row, component);
            Console.WriteLine(row.ToString());
        }
    }

创建代理并将其分配给UIPickerView

var picker = new UIPickerView(UIScreen.MainScreen.Bounds);
picker.DataSource = this;
picker.Delegate = new PickerDelegate();

弱代表:

跳过嵌套类并将选定的UIPicker方法添加到UIViewController并使用Foundation.Export标记:

[Export("pickerView:didSelectRow:inComponent:")]
public void Selected(UIPickerView pickerView, nint row, nint component)
{
    Console.WriteLine(row.ToString());
}

将您的UIViewController指定为弱委托:

var picker = new UIPickerView(UIScreen.MainScreen.Bounds);
picker.DataSource = this;
picker.WeakDelegate = this;
Add(picker);