如何在Xamarin.Forms

时间:2018-05-07 09:45:01

标签: c# xamarin.forms uwp access

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

我在UWP项目中有一个微量计,我想每100ms从模拟输入读取数据。在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项目。请问如何解决这个问题?非常感谢!!!

1 个答案:

答案 0 :(得分:0)

在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。