gpt4 book ai didi

wpf - 使用 MVVM 对 Listbox 的静态项进行命令

转载 作者:行者123 更新时间:2023-12-03 10:14:11 24 4
gpt4 key购买 nike

我的 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)来绑定(bind)SelectedItemListBox到您的 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 对 Listbox 的静态项进行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16139243/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com