2013-06-27 48 views
0

我是MVVM的新手,在這裏我有點頭痛。英語不是我的首選語言,請耐心等待。MVVM的新手WPF,從外部源獲取數據

我正在嘗試爲PLC製作HMI。我應該連接到兩個不同的PLC,並在PLC中顯示來自不同數據塊的數據。爲了簡單起見,我們只討論只連接到一個PLC,並且只從一個數據塊獲取數據。數據塊有一個重複的數據結構,在我的解決方案中,我將每個結構變成一個對象。

對於與PLC的通信,我使用Libnodave。適用於MVVM的MVVM Light。

型號。

包含PLC結構的「配方」。它還包括get-set-methods。

int _startByte; 
string _name; 
int _value1; 
bool value2; 

ViewModel。

來自ViewModelBase的Iherits,並且有一個Model對象作爲成員。公共get-set-methods,在集合上引發propertychanged。 實例:

Public ViewModel(string name, int startByte) 
{ 
     _model = new Model{Name = name, StartByte = startByte}; 
} 


public int Value 
{ 
     get{return _model.Value;} 
     set 
     { 
       if(_model.Value!=value) 
       { 
         _model.Value=value; 
         RaisePropertyChanged("Value"); 
       } 
     } 
} 

CollectionViewModel。

ObservableCollection of ViewModels。從ModelData.cs獲取模型名稱和起始字節(一個具有兩個數組的類,名稱和startbyte)。使用RelayCommands我已經測試了將ViewModel添加到集合中。

查看。

工程現在,並且有希望工作以後還有

我的計劃看起來有點像這樣:

View 
CollectionViewModel 
ViewModel ModelData 
Model 

(視圖模型和ModelData不知道對方)

所以,收集數據。 我的計劃是讓ViewModel引用一個PLC對象(這是Libnodave的地方),並使用PLC對象方法收集數據。 PLC對象表示與PLC的連接,幷包含寫入和讀取數據的方法。在ViewModel中,我將使用PLC對象方法來收集數據(並寫入數據)。

這意味着很多PLC參考,但鎖定將有望防止崩潰。我的問題是我無法弄清楚如何賦予ViewModel一個PLC對象的引用。 PLC對象也將被其他ViewModel使用,並且會有兩個不同的PLS對象,每個PLC對應一個對象。

這是一種有效的方法,還是應該尋找完全不同的東西?

回答

0

如果我理解正確的話,你有一個PLC,以在其內的數據結構的陣列,並且每個數據結構會被物體在你的程序中來表示。現在把它乘以兩,因爲你有兩個PLC。

對於這個帖子的緣故,讓我們把代表一個PLC PLC類。讓我們調用表示PLC中的單個結構的每個對象PLCData

創建一個包含一個包含兩個PLC對象的數組的單例類(或靜態類)。每個PLC對象具有PLCData對象的數組(或列表<>或...)。

現在,您的視圖模型只需要掌握單例或靜態類的實例,這很容易實現。

如果您使用多線程(每個PLC使用一個線程來收集數據),那麼BlockingCollection作爲您的對象的數據結構可能是一個不錯的選擇。

0

我認爲TS正在尋找解決方案來查詢他的PLC。如果你問我你正在尋找一個Repository pattern。這是獲取所有數據的好方法。這可以在不同的ViewModels或其他地方重用。

在你的版本庫的方法將返回您的PLC數據

的(數據)模型的實例,讓您擁有一個名爲PlcRepository 與方法類的GetData(對象的PLCID),您可以用替換對象一些有用的東西,可以確定你試圖查詢哪個Plc。這樣做的全部邏輯就是從PLC獲取數據並將返回對象Libnodave庫/ api

public class PlcRepository : SomeBase 
{ 
    public PlcRepository() 
    { 
     //Do what you need to do 
    } 

    /// <summary> 
    /// Query the data from your PLC 
    /// </summary> 
    /// <param name="plcId">The ID of the PLC to query</param> 
    /// <returns>PlcData</returns> 
    public PlcData GetData(object plcId) 
    { 
     PlcData data = new PlcData() 

     //create instance of your class that is able to talk to the PLC 

     //Query your plc 

     //Fill your dataobject 

     //return the dataobject you just filled 
     return data; 
    } 
} 

public class MainViewModel 
{ 
    private readonly PlcRepository _plcRepository; 

    public MainViewModel() 
    { 
     // Create instance of your Repository 
     _plcRepository = new PlcRepository(); 

     // Get the Data from the PLC Repository and fill your property 
     PlcData = _plcRepository.GetData(12345); 
    } 

    public PlcData PlcData { get; set; } 
}