如何从 Xamarin.Forms 中的 UWP 访问 PCL 中的参数



我正在使用Xamarin Forms与I2C设备和Raspberry Pi结合使用。我用C#编程,Raspberry Pi是与Windows IoT一起安装的。而且我遇到了有关参数访问的问题。

我在 UWP 项目中有一个微型计时器,我想每 100 毫秒从模拟输入读取一次数据。在 OnTimedEvent 中,有一个计算需要 PCL 项目中设置的一些参数,命名空间为 "I2CADDA。MainPage.xaml.cs"。我尝试将这些参数设置为公共静态。

public static double gainFactor = 1;
public static double gainVD = 1;

而在UWP项目中,我使用依赖服务,因为我必须使用微计时器,所以接口的实现是在"I2CADDA"中完成的。UWP。MainPage.xaml.cs",在函数OnTimedEvent中,我尝试从PCL项目文件中获取参数。

public void OnTimedEvent(object sender, MicroLibrary.MicroTimerEventArgs timerEventArgs)
{
byte[] readBuf = new byte[2];
I2CDevice.ReadI2C(chan, readBuf); //read voltage data from analog to digital converter
sbyte high = (sbyte)readBuf[0];
int mvolt = high * 16 + readBuf[1] / 16;
val = mvolt / 204.7 + inputOffset;
val = val / gainFactor / gainVD; //gainFactor and gainVD shows not exist in current context
}

UWP 项目似乎无法以正常方式访问 PCL 项目。请问我该如何解决这个问题?谢谢!!!

在 C# 中,要调用静态字段,应使用类名来调用它,

在代码中,静态字段位于I2CADDA中。MainPage.xaml.cs,例如,它们在I2CADDA.MainPage类中,您可以将该字段称为

double Factor = I2CADDA.MainPage.gainFactor;
double VD = I2CADDA.MainPage.gainVD;

所以你上面的代码应该是这样的:

public void OnTimedEvent(object sender, MicroLibrary.MicroTimerEventArgs timerEventArgs)
{
byte[] readBuf = new byte[2];
I2CDevice.ReadI2C(chan, readBuf); //read voltage data from analog to digital converter
sbyte high = (sbyte)readBuf[0];
int mvolt = high * 16 + readBuf[1] / 16;
val = mvolt / 204.7 + inputOffset;
val = val / I2CADDA.MainPage.gainFactor / I2CADDA.MainPage.gainVD; 
}

另请确保在 UWP 项目中引用了 PCL。

最新更新