2014-08-30 61 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

相關問題