我正在使用MVVM设计模式开发WPF应用程序.在应用程序中,我有一个ItemsControl,它显示了几个按钮(根据应用程序的逻辑流程,按钮数量不是恒定的).ItemsControl绑定到ViewModel中的LinkedList.我能够为Buttons定义一个Command,只有在Command没有参数的情况下我才能在ViewModel中获取Command处理程序......我需要能够知道哪个按钮被点击了,因此我想要带参数的命令.
我如何定义我的视图?CommandParameter的语法是什么,我可以使用哪个参数来获取Button内容?ViewModel中的Command签名是什么?
请注意,我正在使用MVVM Light中的RelayCommand.View的relvant代码就在这里.提前致谢
<UserControl x:Class="Museum.Controls.CategoriesView"
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"
mc:Ignorable="d"
d:DesignHeight="130" d:DesignWidth="418">
<UserControl.Resources>
<DataTemplate x:Key="CategoriesButtonsTemplate">
<Button Content="{Binding }"
Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}, Path=DataContext.CategorySelectedCommand}"
/>
</DataTemplate>
</UserControl.Resources>
<Grid ShowGridLines="True">
<Grid.RowDefinitions>
<RowDefinition Height="50"></RowDefinition>
<RowDefinition Height=" 40"></RowDefinition>
<RowDefinition Height=" 40"></RowDefinition>
</Grid.RowDefinitions>
<Grid x:Name="SubSubjectGrid" Grid.Row="0"></Grid>
<Grid x:Name="CategoriesGrid" Grid.Row="1">
<ItemsControl Grid.Row="1"
ItemsSource="{Binding Path=CategoriesButtons}"
ItemTemplate="{StaticResource CategoriesButtonsTemplate}" >
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</Grid>
<Grid x:Name="SelectedCategoryGrid" Grid.Row="2"></Grid>
</Grid>
</UserControl>
Run Code Online (Sandbox Code Playgroud)
您可以像这样简单地使用CommandParameter ="{Binding}"
<DataTemplate x:Key="CategoriesButtonsTemplate">
<Button Content="{Binding }"
Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}, Path=DataContext.CategorySelectedCommand}"
CommandParameter="{Binding }"
/>
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17691 次 |
| 最近记录: |