我的 View 中有一个列表框,其中包含三个静态项目(姓名、年龄、性别),我希望我的 ViewModel 在选择列表框中的项目时执行某些操作。我想使用 MVVM 模式在没有任何代码隐藏的情况下完成此操作。
我的目标是在选择某个项目时导航到页面,而且上述项目并非来自可观察列表,它是在我的 XAML 中硬编码的。我该怎么做呢?请教我。如果您不介意发送 sample ,那将是一个很大的帮助。非常感谢。
<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>
最佳答案
您可以使用数据绑定(bind)将 ListBox
的 SelectedItem
绑定(bind)到 View 模型上的属性。然后,在 View 模型属性的 setter 中,您可以在所选项目更改时运行所需的逻辑。
<ListBox SelectedItem="{Binding MySelectedItem}" ... />
更新
好吧,首先我强烈建议(不坚持)您使用 MVVM 框架。 If you're doing MVVM, then you need to use a framework .
接下来,这些列表项没有理由不能出现在您的 View 模型上。这肯定会让你的视野变得更加清晰。
然后,您可以将 ListBox
ItemsSource
设置为绑定(bind)到 View 模型集合,然后在 View 中使用数据模板来一致地呈现列表中的每个项目。
例如你的 View 最终可能会是这样的:
<ListBox ItemsSource="{Binding MyItems}" SelectedItem="{Binding MySelectedItem}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Value}" ... />
<TextBlock Text="{Binding Description}" ... />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
更加干净,我想你会同意的。
关于wpf - 使用 MVVM 对列表框的静态项目进行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16139243/