Xamarin从渲染器Button更改页面

时间:2014-11-18 13:33:50

标签: ios mono xamarin.ios xamarin xamarin-studio

我在iOS中有一个渲染器按钮,我想要做的是在获取滑动手势时触发另一个页面进入堆栈。

如果我在我的MainPage上实现它,对于Clicked来说它很安静。因为我可以使用“这个”

    public class MainPage : ContentPage
    {
        public MainPage ()
        {
            // Button bottom 1
            var button = new Button { 
                Text = "button",
                HeightRequest = 60,
                HorizontalOptions = LayoutOptions.FillAndExpand,
                VerticalOptions = LayoutOptions.CenterAndExpand,

            };
            button.Clicked += async (sender, e) => {
                await this.Navigation.PushModalAsync(new nextPage());
            };
       }
}

但我怎么能在iOS中的渲染按钮中执行此操作。

我的渲染器按钮是这样的:

public class MYButtonRenderer : ButtonRenderer
    {
        UISwipeGestureRecognizer swipeGestureRecognizerUp;

        protected override void OnElementChanged (ElementChangedEventArgs<Button> e)
        {
            base.OnElementChanged (e);

            swipeGestureRecognizerUp = new UISwipeGestureRecognizer (() => onSwipeUp());
            swipeGestureRecognizerUp.Direction = UISwipeGestureRecognizerDirection.Up;

            if (e.NewElement == null) 
            {

                if (swipeGestureRecognizerUp != null) 
                {
                    this.RemoveGestureRecognizer (swipeGestureRecognizerUp);
                }
            }

            if (e.OldElement == null) 
            {
                this.AddGestureRecognizer (swipeGestureRecognizerUp);
            }
        }

        private void onSwipeUp()
        {
           //here it's where I would like to change the page to a new one.
        }
    }

这可能吗? 谢谢你的时间。

1 个答案:

答案 0 :(得分:2)

一种很好的方法是将自定义渲染器与自定义按钮视图结合使用。您的自定义视图可能包含您可以订阅的滑动事件。当然,如果需要,您也可以创建自定义委托,以传递自定义事件数据,但我保持此示例简单。

public class CustomButton : Button
{
    public event EventHandler OnSwipeUp;

    public void FireSwipeUp()
    {
        var swipeUp = OnSwipeUp;
        if (swipeUp != null)
            swipeUp(this, EventArgs.Empty);
    }
}

在自定义渲染器中,您可以通过调用FireSwipeUp方法触发自定义事件。

private void onSwipeUp()
{
    ((CustomButton)Element).FireSwipeUp();
}

现在,您可以在OnSwipeUp课程中订阅自定义MainPage活动,就像使用Clicked一样。

// Button bottom 1
var button = new CustomButton { 
    Text = "button",
    HeightRequest = 60,
    HorizontalOptions = LayoutOptions.FillAndExpand,
    VerticalOptions = LayoutOptions.CenterAndExpand,
};

button.Clicked += async (sender, e) => {
     await this.Navigation.PushModalAsync(new nextPage());
};

button.OnSwipeUp += async (sender, e) => {
     await this.Navigation.PushModalAsync(new nextPage());
};