C# 如何在ViewModel中捕获动态按钮单击
我通过绑定ObservableCollection创建了一组按钮 在我的ViewModel中,我希望捕获单击事件 对于我通常使用的按钮:C# 如何在ViewModel中捕获动态按钮单击,c#,wpf,viewmodel,C#,Wpf,Viewmodel,我通过绑定ObservableCollection创建了一组按钮 在我的ViewModel中,我希望捕获单击事件 对于我通常使用的按钮: RelayCommand launchCommand; public ICommand LaunchCommand{ get{ if (launchCommand == null){ launchCommand = new RelayCommand(LaunchCommandExecute, CanLaunch
RelayCommand launchCommand;
public ICommand LaunchCommand{
get{
if (launchCommand == null){
launchCommand = new RelayCommand(LaunchCommandExecute, CanLaunchCommandExecute);
}
return launchCommand;
}
}
private void LaunchCommandExecute(object parameter){
//Do something to recognize the button.
//Could use ObservableCollection<Module> module_objects
//to match, if I could get the buttons content or name
}
private bool CanLaunchCommandExecute(object parameter){
return true;
}
参数
由命令参数
设置。在这种情况下,只需将其绑定到“ModuleName”:
(请注意,您也可以使用
{Binding RelativeSource={RelativeSource Self},Path=Tag}
将CommandParameter
设置为按钮的标记或内容,但在这种情况下,这是一种迂回的方法。)奇怪的是,我发现我的LaunchCommand没有启动。我进行了编辑,包括XAML。你能看到什么奇怪的东西吗?
<Button Tag="{Binding ModuleName}" Content="{Binding ModuleAbbreviation}" Command="{Binding LaunchCommand}" IsEnabled="{Binding ModuleDisabled}" Style="{DynamicResource LauncherButton}" Background="{Binding ModuleColor}" />
<UserControl.DataContext>
<viewmodel:LauncherViewModel />
</UserControl.DataContext>
<Grid >
<ItemsControl ItemsSource="{Binding Source={x:Static m:ModuleKey._module_objects}}" >
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<my:AlignableWrapPanel HorizontalAlignment="Stretch" Name="alignableWrapPanel1" VerticalAlignment="Center" HorizontalContentAlignment="Center" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Margin="10">
<Button Content="{Binding ModuleAbbreviation}" Command="{Binding LaunchCommand}" CommandParameter="{Binding ModuleName}" IsEnabled="{Binding ModuleDisabled}" Style="{DynamicResource LauncherButton}" Background="{Binding ModuleColor}" FontSize="32" FontFamily="Tahoma" Width="130" Height="100" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
Command="{Binding DataContext.LaunchCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"
<Button Command="{Binding LaunchCommand}" CommandParameter="{Binding ModuleName}" ...
private void LaunchCommandExecute(object parameter){
string moduleName = parameter as string;
// ...
}