mef*_*fiX 6 c# command xamarin xamarin.forms
我有一个非常基本的测试页面SettingsPage,它在 xaml 中包含一个按钮,如下所示:
<Button Text="Toggle Compass" Command="{Binding toggleCompassCmd}"/>
Run Code Online (Sandbox Code Playgroud)
一个类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());
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
在 xaml 类中,我有一个 type 成员CompassTest,它应该接收命令,如下所示:
public SettingsPage()
{
InitializeComponent();
compass = new CompassTest();
}
Run Code Online (Sandbox Code Playgroud)
但是,一切都会编译,但没有任何反应。如何将命令“重定向”给成员?
将您的页面设置BindingContext为持有命令的对象。在你的情况下:
public SettingsPage()
{
InitializeComponent();
compass = new CompassTest();
BindingContext = compass;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6515 次 |
| 最近记录: |