It depends on the MVVM library that you are using or your own implementation.
1. Most MVVM libraries have a message broker to pass strongly-typed data between different parts of your applications, like between ViewModels. Here is the MVVM Community Toolkit documentation on their implementation:
Messenger - .NET Community Toolkit | Microsoft Learn[
^]
2. Alternatively, if you are using
Dependency Injection[
^], you can use a Singleton dependency class to hold the shared data and inject that into your ViewModels that need to share the data.
public class SharedDataStore : ISharedDataStore
{
public some_value_type SomeProperty { get; set; }
}
public interface ISharedDataStore
{
some_value_type SomeProperty { get; set; }
}
Now you can set up the dependencies:
HostApplicationBuilder builder = Host.CreateApplicationBuilder();
builder.Services.AddSingleton<ISharedDataStore, SharedDataStore>();
IHost host = builder.Build();
Then inject in to the ViewModel:
public class MyViewModel : ViewModelBase
{
private ISharedDataStore _sharedData;
public MyViewModel(ISharedDataStore sharedData)
{
this._sharedData = sharedData;
}
public void DoSomething()
{
this._sharedData.SomeProperty = some_value;
}
}
3. If not using dependency Injection, then create a static (shared) class manually to hold the shared data. Then each ViewModel can access the static class.
public static class SharedDataStore
{
public some_value_type SomeProperty { get; set; }
}
Then in your ViewModel, you can access the shared data:
public class MyViewModel : ViewModelBase
{
public void DoSomething()
{
SharedDataStore.SomeProperty = some_value;
}
}
Hope this helps!