2011-11-11 86 views
3

我試過閱讀文章WPF/Silverlight: Step By Step Guide to MVVM,但我完全無法理解它。將View代碼保留在View代碼中不好嗎?

但是我noticied這樣的方針:

那是你的View.xaml.cs是應該幾乎沒有代碼。

我該如何修復下面的代碼?我應該將我的WCF代碼解壓到另一個地方嗎?謝謝。

/// <summary> 
/// Interaction logic for MainWindow.xaml 
/// </summary> 
public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 
    } 

    private void Window_Loaded(object sender, RoutedEventArgs e) 
    { 
     ChannelFactory<IManagementConsole> pipeFactory = 
       new ChannelFactory<IManagementConsole>(
        new NetNamedPipeBinding(), 
        new EndpointAddress(
         "net.pipe://localhost/PipeManagementConsole")); 

     IManagementConsole pipeProxy = 
      pipeFactory.CreateChannel(); 

     List<ConsoleData> datas = new List<ConsoleData>(); 
     foreach (StrategyDescriptor sd in pipeProxy.GetStrategies()) 
     { 
      datas.Add(pipeProxy.GetData(sd.Id)); 
     } 
     dataGrid1.ItemsSource = datas; 
    } 
} 
+0

爲什麼你在視圖中使用WCF代碼?這看起來像很糟糕的設計... –

+0

看起來是重複http://stackoverflow.com/questions/3878610/why-keep-code-behind-clean-and-do-everything-in-xaml –

回答

1

是的,這是不好的做法,尤其是從MVVM的角度來看。

提取所有的業務邏輯到ServiceViewModel類,在查看剛纔設置視圖模型的實例的DataContext:

public MainWindow() 
{ 
     InitializeComponent(); 
     this.DataContext = new ServiceViewModel(); 
} 

如果您有其他類/窗口,它是實例化這個窗口中,您應該在設置視圖模型它。例如:

MyWindow childWindow = new MyWindow(); 
childWindow.DataContext = new ServiceViewModel(); 

所以,現在你可以看到MVVM在行動上,在主窗口XAML文件,你可以使用綁定象下面這樣:

<!-- Considering that ServiceViewModel has 
    public string ServiceName property 
--> 
<TextBlock Text="{Binding ServiceName}" /> 

<!-- Considering that ServiceViewModel has 
    public List<ConsoleData> DataItems property 
--> 
<DataGrid ItemsSource="{Binding DataItems}" /> 

這樣你的邏輯留在視圖模型和視圖分離。

PS:

我會建議使用ObservableCollection<ConsoleData>爲ConsoleData名單,好處是:(MSDN

的ObservableCollection類

表示一個動態數據採集,提供通知時 項目添加,刪除或整個列表刷新時。

+0

謝謝,可以我在xaml中設置了DataContext並消除了最後一行代碼?如何實現ServiceViewModel?歡迎鏈接到相應的文檔。 – javapowered

+0

@javapowered:看到剛剛更新的答案,基本上你的ViewModel應該公開'ObservableCollection DataItems'然後只是綁定它在XAML中,如答案 – sll

+0

所示是的,你可以在XAML中設置DataContext。您需要添加一個名稱空間參考,並在參考資料部分創建一個ViewModel類的實例。然後你將DataContext綁定到該資源。 –

相關問題