2013-04-22 48 views
2

我有我有三個靜態項目(姓名,年齡,性別)查看列表框,我想在選擇ListBox中的一個項目我的視圖模型做一些列表框的靜態項目指揮。我想在沒有任何代碼隱藏的情況下使用MVVM模式。使用MVVM

我的目標是當也選擇了一個項目上面所述並非來自可觀察到列表中的項目導航到一個頁面,它在我的XAML是固定的。我會怎麼做?請教我。如果你不介意發送樣本,這將是一個很大的幫助。非常感謝。

<ListBox x:Name="lbviewlist"> 
    <i:Interaction.Triggers> 
     <i:EventTrigger EventName="SelectionChanged" > 
      <Command:EventToCommand Command ="{Binding ViewCommand}" 
       PassEventArgsToCommand="True"/> 
     </i:EventTrigger> 
    </i:Interaction.Triggers> 
    <ListBox.Items> 
     <StackPanel x:Name="lbiview1" Orientation="Vertical"> 
      <ListBoxItem Content="Name" FontSize="35" Margin="10,0,0,0" 
       Foreground="OrangeRed"/> 
      <TextBlock TextWrapping="Wrap" Text="View name of the patient" 
       FontSize="25" Margin="10,0,0,0" Foreground="White"/> 
     </StackPanel> 
     <StackPanel x:Name="lbiview2" Orientation="Vertical"> 
      <ListBoxItem Content="Age" FontSize="35" Margin="10,20,0,0" 
       Foreground="OrangeRed"/> 
      <TextBlock TextWrapping="Wrap" Text="View age of the patient" 
       FontSize="25" Margin="10,0,0,0" Foreground="White"/> 
     </StackPanel> 
     <StackPanel x:Name="lbiview3" Orientation="Vertical"> 
      <ListBoxItem Content="Gender" FontSize="35" Margin="10,20,0,0" 
       Foreground="OrangeRed"/> 
      <TextBlock TextWrapping="Wrap" Text="View the gender of the patient" 
       FontSize="25" Margin="10,0,0,0" Foreground="White"/> 
     </StackPanel> 
    </ListBox.Items>      
</ListBox> 

回答

4

您可以使用數據綁定到ListBoxSelectedItem綁定到您的視圖模型的屬性。然後,在視圖模型屬性的設置器中,可以在選定項目更改時運行所需的邏輯。

<ListBox SelectedItem="{Binding MySelectedItem}" ... /> 

更新

好吧,首先,我會強烈建議(不堅持)您使用的MVVM框架。 If you're doing MVVM, then you need to use a framework

接下來,我們沒有理由爲什麼這些列表中的項目不能上你的視圖模型。這肯定會讓你的觀點更清晰。

然後,您可以將您的ListBoxItemsSource綁定到您的視圖模型集合,然後在視圖中使用數據模板來一致地呈現列表中的每個項目。

E.g.你的看法可能會結束如下:

<ListBox ItemsSource="{Binding MyItems}" SelectedItem="{Binding MySelectedItem}"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <StackPanel> 
      <TextBlock Text="{Binding Value}" ... /> 
      <TextBlock Text="{Binding Description}" ... /> 
      </StackPanel> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox>     

更清潔,我想你會同意。

+0

你願意給我一個例子嗎?非常感謝您的幫助。我只是不知道在哪裏以及如何開始。順便說一下,我在互聯網上看到了不同的例子,但是我的問題是我沒有可綁定到屬性的IObservable集合,因爲我的項目是硬編碼的。請參閱可能的XAML。再次感謝 – JennyJane 2013-04-22 09:44:33

+0

什麼是_view1,_view2和_view3? – devdigital 2013-04-22 09:52:13

+0

這些只是字符串,我把Resources.xaml :) 我可以直接將其更改爲項目的實際字符串/名稱。查看更新的XAML。再次感謝! – JennyJane 2013-04-22 09:55:01