绑定不会更新onPropertyChange

时间:2019-09-03 11:13:36

标签: c# xamarin

我有一个视图模型,在其中我定期从蓝牙模块更新我的参数之一。 (我的设置器中有一个断点,所以我确定它已更新)

参数确实在我的视图模型中正确更新,并且我确定我的绑定在我的视图中正确。

我怀疑我的propertyChanged?方法是使我的代码错误的方法:

 public class Viewmodel : INotifyPropertyChanged
 {
      public Viewmodel()
      {
      }
      public string CurrentValue
      {
           get
           {
                return _currentValue;
             }
             set
             {
                  if (_currentValue!= value)
                  {
                       _currentValue= value;
                       PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(CurrentValue));
                  }
             }
      }
}

查看:

<Label Text="{Binding BindingContext.CurrentValue, Source={x:Reference Name=MyCarousel}}"/>

查看背后的代码:

public partial class View: ContentPage
{
    public TemperaturePage()
    {
        InitializeComponent();
        MyCarousel.BindingContext = new ViewModel();
    }
}

Fyi,我正在使用Xabre BLE来简化连接,更新我的viewmodel的特征侦听器如下所示:

public async void GetValuesFromCharacteristic()
{
    Viewmodel viewModel = new Viewmodel();

    Characteristic.ValueUpdated += (s, a) =>
    {
        Console.WriteLine(Characteristic.Value[7].ToString());

        Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
        {
            viewModel.CurrentValue = Characteristic.Value[7].ToString();
        });
    };
    await Characteristic.StartUpdatesAsync();
}

在我看来,PropertyChanged?保持为空,因此为什么什么都没有更新。

1 个答案:

答案 0 :(得分:0)

Demo所述,PropertyChangedEventArgs的参数应为string,其属性名称已更改。

ViewModel还需要实现INotifyPropertyChanged。它不在您的示例代码中,但是我假设这只是该问题的示例定义。