2011-08-28 78 views
0

我有一些麻煩應用MVVM模式,爲開始我下面這個例子來學習如何應用和使用模式...麻煩應用MVVM模式

http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

所以我的問題是建立「連接」與視圖模型視圖之間...

在這個例子中,我們有一個CollectionViewSource其中源是AllCustomers屬性查看:

<UserControl 
    x:Class="DemoApp.View.AllCustomersView" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"> 
    <UserControl.Resources> 
     <CollectionViewSource x:Key="CustomerGroups" Source="{Binding Path=AllCustomers}"/> 
    </UserControl.Resources> 

    <DockPanel> 
     <ListView AlternationCount="2" DataContext="{StaticResource CustomerGroups}" ItemsSource="{Binding}"> 
      <ListView.View> 
       <GridView> 
        <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=DisplayName}"/> 
        <GridViewColumn Header="E-mail" DisplayMemberBinding="{Binding Path=Email}"/> 
       </GridView> 
      </ListView.View> 
     </ListView>    
    </DockPanel> 
</UserControl> 

誰屬於視圖模型AllCustomersViewModel:

public class AllCustomersViewModel : WorkspaceViewModel 
{ 
    (...) 

    public ObservableCollection<CustomerViewModel> AllCustomers { get; private set; } 

    (...) 
} 

,但他用他適用的視圖和視圖模型之間的一個DataTemplate資源字典:

<DataTemplate DataType="{x:Type vm:AllCustomersViewModel}"> 
    <vw:AllCustomersView /> 
</DataTemplate> 

但我的問題是因爲我沒有使用ResourceDictionary,因爲我認爲我可以把DataTemplate放在窗口的資源中,我將有我的視圖(對於我來說是更多的邏輯放置DataTemplate的地方)...但由於某種原因,數據isn' t出現在ListView中,所以我問爲什麼?

回答

4

我不會在Xaml中附加視圖模型。這將Xaml硬編碼爲特定的視圖模型。

相反,我會重寫應用程序啓動:

private void OnStartup(object sender, StartupEventArgs e) 
{ 
    Views.MainView view = new Views.MainView(); 
    view.DataContext = new ViewModels.MainViewModel(); 
    view.Show(); 
} 

看到這篇文章:

http://www.codeproject.com/KB/WPF/MVVMQuickTutorial.aspx

這種方法也是有幫助的,如果你使用某種工具的動態綁定您的查看未來的模型,如MEF,Castle.Windsor或Prism。

0

DataTemplates不帶密鑰暗示地應用指定的DataType的任何數據作爲要顯示的內容。這意味着您的ViewModel需要顯示在某處,例如ContentControl的內容或ItemsControl的項目。

所以,如果你有一個窗口,你需要有視圖模型的實例在它:

<Window ...> 
    <Window.Resources> 
     <DataTemplate DataType="{x:Type vm:AllCustomersViewModel}"> 
      <vw:AllCustomersView /> 
     </DataTemplate> 
    </Window.Resources> 
    <Window.Content> 
     <vm:AllCustomersViewModel /> 
    </Window.Content> 
</Window> 

通常只使用Windows作爲炮彈雖然和內容是動態設置的。

+0

但是對於我現在所瞭解的模式,我們使用視圖作爲控制權?那麼我們會實例化ViewModel嗎?我有我的代碼的方式,他不會給出任何錯誤或警告,但他不訪問該集合將數據綁定到ListView。我已經建立了一個非常相似的應用程序,並在我的問題中的例子,但適應我想要的... – Miguel

+0

@Miguel:您的代碼不會顯示任何列表視圖,只顯示您創建CollectionViewSource的方式,也不管創建視圖,然後創建視圖模型或其他方式由您決定,如果您爲視圖模型創建數據模板意味着您先創建視圖模型。 –

+0

是不顯示我使用ListView的任何地方,但我有我的應用程序在我的問題鏈接的MvvmDemo。所以我在一個ListView中使用虛擬機,所以我不需要對它進行灌輸?所以我錯過了什麼?!我正在做的唯一不同於鏈接的示例是,我沒有使用ResourceDictionary ... – Miguel

1

我永遠不會將我的視圖模型綁定到我在XAML中的視圖。我更願意控制自己設置綁定的時間。我總是在視圖上放置一個屬性,該屬性包含對視圖模型的引用。這樣我可以根據需要更改視圖模型,而不會由於XAML綁定而產生任何不確定的後果。此外,通過這種方式,我可以在視圖模型上放置一個INotify處理程序,以便在切換視圖模型時自動更新所有更改。