我有Wpf窗口和相应的ViewModel
。 MainWindow
上有一个绑定到属性CurrentActionTaken
private string _CurrentActionTaken;
public string CurrentActionTaken
{
get{
return _CurrentActionTaken;
}
set{
_CurrentActionTaken = value;
OnPropertyChanged("CurrentActionTaken");
}
}
我有BackgroundWorker
在同一个viewmodel中调用私有方法WorkerDoWork
_Worker = new BackgroundWorker();
...
_Worker.DoWork += (obj, e) => WorkerDoWork(_selectedEnumAction, _SelectedCountry);
_Worker.RunWorkerAsync();
在WorkerDoWork
内部我想调用其他需要努力工作的类,我想在我的MainWindow
标签上显示当前处理项目(绑定到CurrentActionTaken
属性)
private void WorkerDoWork(Enums.ProviderAction action, CountryCombo selCountry)
{
_CurrentActionTaken = "entered WorkerDoWork method";
OnPropertyChanged("CurrentActionTaken");
new MyOtherClass(_selectedEnumAction, _SelectedCountry);
...
}
这里我想使用将在OtherClass
数据迭代方法上调用的方法:
public static void DataProcessUpdateHandler(string item)
{
MessageBox.Show(item);
}
最后在OtherClass
中的某处迭代调用:
foreach (var item in items)
{
...
MainViewModel.DataProcessUpdateHandler(item.NameOfProcessedItem);
}
一切都适合在MessageBox
DataProcessUpdateHandler
内的项目
MessageBox.Show(item);
我的问题是如何改变这一点并使用
_CurrentActionTaken = item;
OnPropertyChanged("CurrentActionTaken");
现在它不可能因为DataProcessUpdateHandler
是静态方法。
答案 0 :(得分:1)
这是一种快速而又肮脏的方式:
(Application.Current.MainWindow.DataContext as MainViewModel).CurrentActionTaken = "Executing evil plan to take control of the world."
当然,如果您的MainViewModel
可以通过MainWindow内的属性访问,那么您应该进行调整:
Application.Current.MainWindow.Model.CurrentActionTaken = "Executing evil plan to take control of the world."
"正确"方法是传递你的视图模型(或任何其他中间对象),但如果你想保持简单并且可以使用上面的方法,那么恕我直言就无法制作更复杂的东西了。
编辑:根据您要求更清洁,您可以绕过VM:
private void WorkerDoWork(Enums.ProviderAction action, CountryCombo selCountry)
{
_CurrentActionTaken = "entered WorkerDoWork method";
OnPropertyChanged("CurrentActionTaken");
new MyOtherClass(_selectedEnumAction, this);
...
}
MyOtherClass
实例可以访问整个VM:_SelectedCountry
和CurrentActionTaken
。
您可以进一步定义ISupportCurrentActionTaken
界面,将MyOtherClass
与MainViewModel
分开,但如果他们住在同一个项目中,这显然有点过分。