Reputation: 39
I encountered some issue when I have some loaded a list from my logic and want to select some values from this list using a different viewModel.
public List<ContactsListModel> ExampleList
{
get => _exampleList;
set
{
_exampleList = value;
PropertyChanged(this, new PropertyChangedEventArgs(nameof(ExampleList)));
}
}
Above we have my list, which contains some data. I dont want to load it once again. How can I get values from it in a different viewModel?
Upvotes: 0
Views: 1029
Reputation: 11
I put things in a base class then inherit from base class, inheriting List. I'm kind of new to Xamarin, So Not sure if this is recommended?
public IDataStore<Item> DataStore =>
DependencyService.Get<IDataStore<Item>>();
public ObservableCollection<Item> Items { get; }
bool isBusy = false;
public BaseViewModel()
{
Items = new ObservableCollection<Item>();
}
Upvotes: 1
Reputation: 1474
Simplest way would be is to pass your view model instance to your view wherever required. However, the best way is to use any MVVM patters and register your instance using container.
Am using MVVM Light and there is a option there to use the SimpleIoc container there. Just register your ViewModels and get unique instances of your ViewModel anywhere require.
I have my ViewModels registered in a class called ViewModelLocator like below.
public LoginViewModel LoginVM
{
get
{
if (!SimpleIoc.Default.IsRegistered<LoginViewModel>())
{
SimpleIoc.Default.Register<LoginViewModel>();
}
return SimpleIoc.Default.GetInstance<LoginViewModel>();
}
}
And I have a property called Locator in my App.cs like below.
public static ViewModelLocator Locator
{
get { return _locator ?? (_locator = new ViewModelLocator()); }
}
So anywhere required now, I can access the ViewModel as below.
App.Locator.LoginVM.[PropertyName] = [values to assign];
Upvotes: 0
Reputation: 1267
You can pass the instance of your view model to the page where you want to use it, from there you can access it.
1. The Viewmodel you want to access:
Pushasync(new YourPage(this)); //Passed the instance of your view model
2. The page where you want to access:
public partial class DemoClass
{
YourViewModel demo_;
public DemoClass()
{
InitializeComponent();
}
public DemoClass(Yourviewmodel demo)
{
InitializeComponent();
demo_ = demo; // access the instance and all its properties
}
}
Upvotes: 0