从不同的 ViewModel 访问首选项

Access preferences from different ViewModels

我有 SettingsViewModel:

  public class SettingsViewModel : BaseViewModel, ISettingsViewModel
  {
    public SettingsViewModel()
    {
    }

    private string _gaugeColor;
    public string GaugeColor
    {
      get => Preferences.Get("GaugeColor", "#17805d");
      set
      {
        Preferences.Set("GaugeColor", value);
        this.OnSettingsChanged();
        this.OnPropertyChanged();
      }
    }

    public event EventHandler<SettingsChangedEventArgs> SettingsChanged;
    private void OnSettingsChanged() => this.SettingsChanged?.Invoke(this, new SettingsChangedEventArgs(this.Settings));

    public Settings Settings { get; private set; }
  }
}

我用十六进制字符串设置颜色。

然后在 PanelViewModel 中我有:

private Color _gaugeColor;
public Color GaugeColor
{
  get => Color.FromHex(Preferences.Get("GaugeColor", "#17805d"));
  set
  {
    _gaugeColor = value;
    OnPropertyChanged();
  }
}

现在,如果我在 UI 的“设置”视图中更改 HEX 字符串,在我重新启动应用程序之前,PanelViewModel 中的颜色不会改变。 问题是:在 SettingsViewModel 中更改颜色后,如何立即在 PanelViewModel 中更改颜色?

我试图将它添加到 PanelViewModel 中,但显然这会创建一个新的 SettingsViewModel 实例,并且 Color 不会跟随到 PanelViewMode 中。也许有一些直接的解决方案,但我使用的 Xamarin.Essentials 错了?

public PanelViewModel()
{
  this.SettingsViewModel = new SettingsViewModel();
  this.SettingsViewModel.SettingsChanged += OnSettingsChanged;
}

private Color _gaugeColor;
public Color GaugeColor
{
  get => Color.FromHex(Preferences.Get("GaugeColor", "#17805d"));
  set
  {
    _gaugeColor = value;
    OnPropertyChanged();
  }
}

private void OnSettingsChanged(object sender, SettingsChangedEventArgs e)
{
  this.GaugeColor = Color.FromHex(e.Settings.GaugeColor);
}

private SettingsViewModel SettingsViewModel { get; }

https://docs.microsoft.com/en-us/dotnet/api/xamarin.essentials.preferences?view=xamarin-essentials

Question is: How to make color change in PanelViewModel right after it has been changed in SettingsViewModel?

是的,一个简单的方法是使用MessagingCenter

MessagingCenter class 实现了 publish-subscribe 模式,允许 message-based 不方便通过对象和类型引用 link 的组件之间进行通信。这种机制允许发布者和订阅者在没有相互引用的情况下进行通信,有助于减少它们之间的依赖性。

您可以参考以下代码:

SettingsViewModel.cs中,我们可以在它的构造函数中发布消息,如下:

public class SettingsViewModel
{
    public string Title { get; set; }

    public SettingsViewModel() {

        Title = "SettingsView";

        MessagingCenter.Send<Object, Color>(this, "Hi", Color.Yellow);
    }

}

并且在PanelViewModel.cs ,我们可以订阅这条消息:

public class PanelViewModel
{
    public string Title { get; set; }

    public PanelViewModel() {

        Title = "PanelView";

         MessagingCenter.Subscribe<Object, Color>(this, "Hi", async (sender, arg) =>
        {
            System.Diagnostics.Debug.WriteLine("----->  receive color= " + arg); 
      
         // here ,we can use the received color to update the UI 

        });
    }

}

注:

一旦我们接收到颜色,我们就可以使用接收到的颜色来更新UI,PanelViewModel.cs中的颜色字段应该实现接口INotifyPropertyChanged.