使用委托从其他类更新wpf标签信息

时间:2014-08-30 12:40:57

标签: c# .net wpf

我有Wpf窗口和相应的ViewModelMainWindow上有一个绑定到属性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是静态方法。

1 个答案:

答案 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:_SelectedCountryCurrentActionTaken

您可以进一步定义ISupportCurrentActionTaken界面,将MyOtherClassMainViewModel分开,但如果他们住在同一个项目中,这显然有点过分。