从后台代码更新Xamarin页面标签(另一个类)

时间:2018-07-05 12:17:31

标签: xamarin xamarin.forms

我有一个内容页面类,其中包含一些表格。现在,我还有另一个类,必须更改页面类中的表单,例如更改标签文本或更新listview。

  

测试类:

public class testClass
{
    testPage localpage;
    public void changeText(string txt)
    {
        localpage.bPumpDrv = Convert.ToByte(txt);
        localpage.testBtn.Text = txt;
    }
    public testClass(testPage testPagek)
    {
        localpage = testPagek;
    }
}
  

测试页:

public class testPage : ContentPage, INotifyPropertyChanged
{
    public byte i;
    public Label testLabel;
    public Button testBtn;
    public byte _bPumpDrv;
    public byte bPumpDrv { get { return _bPumpDrv; } set { _bPumpDrv = value; NotifyPropertyChanged("bPumpDrv"); } }
    public new event PropertyChangedEventHandler PropertyChanged;
    public void NotifyPropertyChanged(string info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }

    public testPage()
    {
        testClass testC = new testClass(this);
        this.Title = "test";
        testLabel = new Label
        {
            Text = "0"
        };

        testLabel.SetBinding(Label.TextProperty, new Binding("bPumpDrv", source: this));

        testBtn = new Button
        {
            Text = "0"
        };

        testBtn.Clicked += (object sender, EventArgs e) => 
        {
            i += 1;
            testC.changeText(i.ToString());
        };

        this.Content = new StackLayout
        {
            Children = 
            {
                testLabel
            }
        };
    }
}

当我单击按钮时,标签和按钮文本均保持不变,即“ 0”。

请给我一些提示,谢谢!

1 个答案:

答案 0 :(得分:0)

尝试

testBtn.Clicked += (object sender, EventArgs e) => 
    {
        Xamarin.Forms.Device.BeginInvokeInMainThread( () =>
        {
            testC.changeText(i.ToString());
        });
    };