我目前在两个ViewModel之间通信方面遇到了问题。
下载我的应用程序以查看问题: http://www76.zippyshare.com/v/26081324/file.html
我有两个视图。
这意味着当我点击按钮时,将调用ChangeValueCommandExecute()。该命令将调用fwm.Calculate()并设置新的总和(= Ergebnis)。问题在于,当调用Calculate()时,“One”和“Two”的值始终为“0”。那么我如何在一个ViewModel中调用另一个ViewModel的方法?
编辑:为了明确起见:我想调用FirstViewModel()的方法'Calculate()',而不使用'new FirstViewModel()'!
一个名为'MainView.xaml'的视图,其数据上下文为'MainViewModel'。
一个名为'FirstView.xaml'的视图,其数据上下文为'FirstViewModel'。
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));
}
}
正如您看到的,每当属性'One'或'Two'的值被更改时,它都会调用Calculate()方法。现在我想要的是,当我在MainView中点击一个按钮时,MainViewModel必须调用FirstViewModel中的Calculate()方法。因此,我注释了属性中的Calculate()方法,并在MainViewModel中实现了一个RelayCommand:
MainView中的按钮
<Button Grid.Row="3" Command="{Binding ChangeValue}" />
主视图模型
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();
}
}
这意味着当我点击按钮时,将调用ChangeValueCommandExecute()。该命令将调用fwm.Calculate()并设置新的总和(= Ergebnis)。问题在于,当调用Calculate()时,“One”和“Two”的值始终为“0”。那么我如何在一个ViewModel中调用另一个ViewModel的方法?
编辑:为了明确起见:我想调用FirstViewModel()的方法'Calculate()',而不使用'new FirstViewModel()'!