Xamarin按钮命令绑定

时间:2018-12-10 14:17:01

标签: c# xamarin xamarin.forms command

我有一个非常漂亮的基本测试页面,名为SettingsPage,它在xaml中包含一个按钮,如下所示:

<Button Text="Toggle Compass" Command="{Binding toggleCompassCmd}"/>

CompassTest实现INotifyPropertyChanged并添加一个名为toggleCompassCmd的新命令:

using System;
using System.ComponentModel;
using System.Windows.Input;
using Xamarin.Essentials;
using Xamarin.Forms;

namespace HelloWorld.Models
{
public class CompassTest : INotifyPropertyChanged
{
    // Set speed delay for monitoring changes.
    SensorSpeed speed = SensorSpeed.UI;

    public ICommand toggleCompassCmd { private set; get; }

    private CompassData m_data;
    protected CompassData compassData
    {
        get { return m_data; }
        private set { m_data = value; }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public CompassTest()
    {
        // Register for reading changes, be sure to unsubscribe when finished
        Compass.ReadingChanged += onCompassReadingChanged;

        // setup toggle command
        toggleCompassCmd = new Command(
            execute: () =>
            {
                Console.WriteLine("This is execute of toggleCompassCmd!");
                toggleCompass();
            },
            canExecute: () =>
            {
                return true;     
            });

    }

    void onCompassReadingChanged(object sender, CompassChangedEventArgs e)
    {
        var data = e.Reading;
        Console.WriteLine($"Reading: {data.HeadingMagneticNorth} degrees");
        // Process Heading Magnetic North

        compassData = data;
        onPropertyChanged("compassData");
    }

    protected void onPropertyChanged(string propName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs("DateTime"));
        }
    }

    public void toggleCompass()
    {
        Console.WriteLine("toggleCompass()");
        try
        {
            if (Compass.IsMonitoring)
                Compass.Stop();
            else
                Compass.Start(speed);
        }
        catch (FeatureNotSupportedException fnsEx)
        {
            Console.WriteLine("FeatureNotSupportedException: " + fnsEx.ToString());
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception: " + ex.ToString());
        }
    }
}
}

在xaml类中,我有一个类型为CompassTest的成员,该成员应接收命令,如下所示:

public SettingsPage()
    {
        InitializeComponent();

        compass = new CompassTest();
    }

但是,所有内容都可以编译,但是没有触发。如何将命令“重定向”到成员?

1 个答案:

答案 0 :(得分:1)

将页面的BindingContext设置为保存命令的对象。对于您的情况:

public SettingsPage()
{
    InitializeComponent();

    compass = new CompassTest();
    BindingContext = compass;
}