gpt4 book ai didi

c# - 从 MainViewModel 调用 ViewModel 的方法

转载 作者:行者123 更新时间:2023-11-30 17:05:41 24 4
gpt4 key购买 nike

我目前在 2 个 ViewModel 之间进行通信时遇到问题。在这里下载我的应用程序以查看问题:http://www76.zippyshare.com/v/26081324/file.html

我有 2 个观点。

  • 带有数据上下文“MainViewModel”的“MainView.xaml”。

  • 带有数据上下文“FirstViewModel”的“FirstView.xaml”。

MainView 有一个带有 Content = FirstView 的 ContentControl。我的 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:

主视图中的按钮

<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 的方法呢?

编辑:要说清楚:我想在不使用“new FirstViewModel()”的情况下调用 FirstViewModel() 的方法“Calculate()”!

最佳答案

我无法查看您的项目,因为它需要 Windows 8,但您确定 FirstViewModel 作为 FirstViewDataContext您在 MainViewModel 中指的是同一个 FirstViewModel 吗?据我所知,您在私有(private)的 MainViewModel 的构造函数中新建了一个 FirstViewModel

关于c# - 从 MainViewModel 调用 ViewModel 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16198491/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com