2014-08-30 36 views
1

我有Wpf窗口和相应的ViewModel。有这势必财产CurrentActionTaken使用委托从其他类更新wpf标签信息

private string _CurrentActionTaken; 
public string CurrentActionTaken 
{ 
    get{ 
     return _CurrentActionTaken; 
    } 
    set{ 
     _CurrentActionTaken = value; 
     OnPropertyChanged("CurrentActionTaken"); 
    } 
} 

我有一个BackgroundWorker它调用私有方法WorkerDoWork同一视图模型

_Worker = new BackgroundWorker(); 
... 
_Worker.DoWork += (obj, e) => WorkerDoWork(_selectedEnumAction, _SelectedCountry); 
_Worker.RunWorkerAsync(); 

Inside无WorkerDoWork我想打电话给其他类将采取上MainWindow标签努力工作,我想在我的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 in DataProcessUpdateHandler

MessageBox.Show(item); 

我的问题是如何改变这一点,并使用

_CurrentActionTaken = item; 
OnPropertyChanged("CurrentActionTaken"); 

现在这是不可能的原因DataProcessUpdateHandler是静态方法。

回答

1

这里是一个快速和肮脏的方式:

Application.Current.MainWindow.Model.CurrentActionTaken = "Executing evil plan to take control of the world." 

“正确”的方法是:

(Application.Current.MainWindow.DataContext as MainViewModel).CurrentActionTaken = "Executing evil plan to take control of the world." 

当然,如果你的MainViewModel是通过主窗口中的属性到达你要适应传递你的视图模型(或任何其他中间对象),但如果你想保持简单并可以使用上面的方法,恕我直言无用做更复杂的东西。

编辑:在您的需求更清洁,你可以绕过VM:

private void WorkerDoWork(Enums.ProviderAction action, CountryCombo selCountry) 
{ 
    _CurrentActionTaken = "entered WorkerDoWork method"; 
    OnPropertyChanged("CurrentActionTaken"); 
    new MyOtherClass(_selectedEnumAction, this); 
    ... 
} 

而且MyOtherClass实例将有机会获得整个VM:_SelectedCountryCurrentActionTaken

你可以进一步定义一个ISupportCurrentActionTaken接口来将MyOtherClassMainViewModel分开,但是如果他们住在同一个项目中,这显然是矫枉过正的。

+0

谢谢,你能向我推荐任何更好的解决方案吗?(有我的问题),它可以更复杂一般但更容易维护。 – user1765862 2014-08-30 15:51:41

+0

@ user1765862我已经编辑了我的答案和详细信息。 – Pragmateek 2014-08-30 16:08:13

相关问题