2

我的视图中有一个包含三个静态项目(姓名、年龄、性别)的列表框,我希望我的 ViewModel 在选择列表框中的项目时执行某些操作。我想使用 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

1 回答 1

4

您可以使用数据绑定将 的 绑定到SelectedItem视图ListBox模型上的属性。然后,在视图模型属性的设置器中,您可以在所选项目更改时运行所需的逻辑。

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

更新

好的,首先我强烈建议(不坚持)您使用 MVVM 框架。如果你在做 MVVM,那么你需要使用一个框架

接下来,这些列表项没有理由不能出现在您的视图模型上。它肯定会让你的视野更清晰。

然后你可以设置你ListBox ItemsSource的绑定到你的视图模型集合,然后在你的视图中使用数据模板来一致地呈现列表中的每个项目。

例如,您的视图最终可能类似于:

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

更干净,我想你会同意的。

于 2013-04-22T09:10:04.920 回答