2013-05-18 46 views
0

我試圖使用EventToCommand來初始化我的ViewModel,但命令沒有觸發。我懷疑這是因爲觸發器部分不在數據綁定容器內,但我怎麼能在我的例子中做到這一點?如果可能,我試圖堅持直接使用XAML。DataBinding和EventToCommand

<Window x:Class="MVVMSample.Home" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:viewModels="clr-namespace:MVVMSample.ViewModels" 
     xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" 
     xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WPF4" 
     d:DataContext="{d:DesignInstance Type=viewModels:HomeViewModel, IsDesignTimeCreatable=True}" 
     mc:Ignorable="d" 
     Title="MainWindow" Height="350" Width="525"> 
    <Window.Resources> 
     <viewModels:HomeViewModel x:Key="ViewModel" x:Name="ViewModel" /> 
    </Window.Resources> 
    <i:Interaction.Triggers> 
     <i:EventTrigger EventName="Loaded"> 
      <cmd:EventToCommand Command="{Binding LoadedCommand}" /> 
     </i:EventTrigger> 
    </i:Interaction.Triggers> 
    <Grid DataContext="{StaticResource ViewModel}"> 
     <TextBlock Text="{Binding PersonCount}" /> 
    </Grid> 
</Window> 
+0

你爲什麼要使用這種方法來初始化你的視圖模型?如果您使用mvvm light,那麼視圖模型定位器會爲您執行此操作。你使用viewmodel作爲datacontext通過viewmodellocator進行綁定。 –

+0

我沒有打算使用ViewModelLocator。我是不是該? –

回答

1

你是對的,在DataContext是問題的一部分,但我會用MVVM光,因爲它的設計解決它。

如果您使用的是MVVM_Light,那麼您應該使用視圖模型定位器。它是框架的主要支柱。我用mvvm light來了解mvvm原理。我非常喜歡它,因爲它非常簡單,讓我儘可能快地學習曲線。

在MVVM光你宣佈你viewmodellocator在App.xaml中

<Application.Resources> 
    <ResourceDictionary> 
     <!--Global View Model Locator--> 
     <vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" /> 
    </ResourceDictionary>    
</Application.Resources> 

然後在您的視圖(無論是用戶控件或窗口等),你「附加」你視圖模型到視圖如下:公告DataContext聲明。

<UserControl x:Class="FTC.View.TrackingListView" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" 
      xmlns:cmd="http://www.galasoft.ch/mvvmlight" 
      mc:Ignorable="d" 
      DataContext="{Binding YourViewModel, Source={StaticResource Locator}}" 
      d:DesignHeight="700" d:DesignWidth="1000"> 

這樣從MVVM光視圖模型定位器可以根據需要創建您的視圖模型的單身或唯一的實例。它也可以使用IOC將服務注入到viewmodel的構造函數中。例如,如果我有一個處理數據模型中的人物對象的視圖模型,我創建一個人物服務,執行CRUD操作,然後在viewmodel構造函數參數中引用它。這使我可以使用假設計時間數據或模型中的實際數據。它也使所有關注的問題解耦,這就是mvvm的目的。

我建議閱讀更多關於MVVM-light框架並從他們的網站galasoft構建樣本之一。

See this video

希望這有助於