Reputation: 1476
I'm trying to change the coordinated in an object I have In a observable collection. I'm using the MVVM model, and in my MainViewModel I'm creating an observable collection. In an different viewModel I wish to acess this observable collection however I get the error:
An object reference is required for the non-static field, method, or property
My problem is, when I change the observable collection to static I get an new Error, because of the way I'm adding the observable collection to my application. So is there a way work around the static part and acess the observable collection?
The code where my Observable collection is created:
public ObservableCollection<CastleViewModel> CastlesInPlay { get; set; }
CastlesInPlay = new ObservableCollection<CastleViewModel>
{
(Adding parameters for CastlesInPlay)
};
The code In which I wish to acess my observable collection:
MainViewModel.CastlesInPlay[0].... = ...;
MainViewModel.CastlesInPlay[0].... = ..;
Both of the classes are ViewModels, but when I add the castleInPlay to the my Views I go behind my views code and add them:
private void AddCastle(CastleViewModel castleVM)
{
canvasCountries.Children.Add(new CastleUserControl() { DataContext = castleVM });
}
private void RemoveCastle(CastleViewModel castleVM)
{
canvasCountries.Children.Remove(canvasCountries.Children.Single(x => ((x as CastleUserControl).DataContext as CastleViewModel) == castleVM));
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
MainViewModel vm = ((MainViewModel)DataContext);
vm.CastlesInPlay.ToList().ForEach(x => AddCastle(x));
vm.AddCastleAction = x => AddCastle(x);
vm.RemoveCastleAction = x => RemoveCastle(x);
}
Upvotes: 1
Views: 1159
Reputation: 65079
CastlesInPlay
isn't static. Therefore, you must supply an instance of the class to access it:
var mainViewModel = new MainViewModel();
mainViewModel.CastlesInPlay ...;
You're accessing it like its static like this (which is wrong):
MainViewModel.CastlesInPlay ...;
Upvotes: 2