我有一个非常漂亮的基本测试页面,名为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();
}
但是,所有内容都可以编译,但是没有触发。如何将命令“重定向”到成员?
答案 0 :(得分:1)
将页面的BindingContext
设置为保存命令的对象。对于您的情况:
public SettingsPage()
{
InitializeComponent();
compass = new CompassTest();
BindingContext = compass;
}