Reputation: 936
I'm currentyl having a problem by communicating between 2 ViewModels. Download my app here to see the problem: http://www76.zippyshare.com/v/26081324/file.html
I have 2 views.
A 'MainView.xaml' with the datacontext 'MainViewModel'.
A 'FirstView.xaml' with the datacontext 'FirstViewModel'.
The MainView has a ContentControl with the Content = FirstView. My FirstViewModel looked something like this:
public class FirstViewModel : ViewModelBase
{
public FirstViewModel()
{
One = "0";
Two = "0";
Ergebnis = 0;
}
private string _one;
public string One
{
get { return _one; }
set
{
if (value != null)
{
_one = value;
Calculate();
RaisePropertyChanged(() => One);
}
}
}
private string _two;
public string Two
{
get { return _two; }
set
{
_two = value;
Calculate();
RaisePropertyChanged(() => Two9;
}
}
private decimal _ergebnis;
public decimal Ergebnis
{
get { return _ergebnis; }
set
{
if (value != null)
{
if (value != _ergebnis)
{
_ergebnis = value;
RaisePropertyChanged(() => Ergebnis);
}
}
}
}
public void Calculate()
{
if (Two != null)
{
for (int i = 0; i < 500; i++)
{
Ergebnis = i;
}
Ergebnis = (decimal.Parse(One) + decimal.Parse(Two));
}
}
As you can see, every time the value of the property 'One' or 'Two' is being changed, it'll call Calculate(). What I want now is that when I click on a button in the MainView, the MainViewModel has to call Calculate() in FirstViewModel. So I commented out the Calculate() in the propertys and implemented a RelayCommand in my MainViewModel:
Button in MainView
<Button Grid.Row="3" Command="{Binding ChangeValue}" />
MainViewModel
public MainViewModel
{
ChangeValue = new RelayCommand(ChangeValueCommandExecute);
}
public RelayCommand ChangeValue { get; private set; }
private FirstViewModel fwm;
private void ChangeValueCommandExecute()
{
//CurrentView = Content of the ContentControl in the MainView, which is FirstView
if (CurrentView.Content.ToString().Contains("FirstView"))
{
fwm.Calculate();
}
}
This means when I click on the Button, ChangeValueCommandExecute() is being called. The Command will call fwm.Calculate() and set the new sum (=Ergebnis). The problem is that when Calculate() is being called, the value of 'One' and 'Two' is always "0". So how do I call a method of a ViewModel in another ViewModel?
Edit: To make it clear: I want to call the method 'Calculate()' of FirstViewModel() without using 'new FirstViewModel()'!
Upvotes: 3
Views: 1347
Reputation: 5465
I can't view your project because it requires Windows 8 but are you sure the FirstViewModel
you have as the DataContext
of your FirstView
is the same FirstViewModel
you're referring to in your MainViewModel
? From what I can see, you're newing up a FirstViewModel
in the constructor of the MainViewModel
which is private.
Upvotes: 2