我有 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();
}
}
Now if I change HEX string from Settings view in UI, color does not change in PanelViewModel until I restart an application. Question is: How to make color change in PanelViewModel right after it has been changed in SettingsViewModel?
I have tried to add this into PanelViewModel, but apparently this creates a new instance of SettingsViewModel and Color does not follow into PanelViewMode. Maybe there is some direct solution and I am using Xamarin.Essentials wrong?
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
uj5u.com熱心網友回復:
問題是:如何在 SettingsViewModel 中更改 PanelViewModel 后立即更改顏色?
是的,一個簡單的方法是使用 MessagingCenter。
該類MessagingCenter實作了publish-subscribe 模式,允許在不方便通過物件和型別參考鏈接的組件之間進行基于訊息的通信。這種機制允許發布者和訂閱者在沒有相互參考的情況下進行通信,有助于減少它們之間的依賴關系。
您可以參考以下代碼:
在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中的顏色欄位。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/449250.html
標籤:c# xamarin xamarin.forms mvvm xamarin.essentials
上一篇:在Xamarin中強制執行主題
