首页 > 解决方案 > 绑定不会更新 onPropertyChange

问题描述

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

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

我怀疑我的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();
    }
}

仅供参考,我正在使用 Xabre BLE 来促进连接,更新我的视图模型的特征监听器如下所示:

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?仍然是空的,因此为什么没有更新。

标签: c#xamarin

解决方案


正如dymanoid所提到的,参数 toPropertyChangedEventArgs应该是string带有已更改属性名称的 a。

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


推荐阅读