如何在ViewModel中捕获动态按钮单击

时间:2013-12-03 17:10:01

标签: c# wpf viewmodel

我通过绑定ObservableCollection< module>创建了一堆按钮。

在我的ViewModel中,我想捕获click事件。

对于我经常使用的按钮:

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;
}

在LaunchCommandExecute中我提出了一些想法。我会对什么对象参数持有感兴趣?这对我有用吗?

该按钮具有以下可用于匹配的绑定:

<Button Tag="{Binding ModuleName}" Content="{Binding ModuleAbbreviation}" Command="{Binding LaunchCommand}" IsEnabled="{Binding ModuleDisabled}" Style="{DynamicResource LauncherButton}" Background="{Binding ModuleColor}" />

有谁知道怎么做?

[编辑] 这是在接受以下答案之后

我发现LaunchCommand没有触发。我想知道下面代码中的任何内容是否有冲突?

<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>

[编辑答案] 没关系我想要做的事情,发现命令无法看到正确的DataContext。添加以下内容对其进行排序:

Command="{Binding DataContext.LaunchCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"

1 个答案:

答案 0 :(得分:1)

parameterCommandParameter设置。在这种情况下,您所要做的就是将其绑定到“ModuleName”:

<Button Command="{Binding LaunchCommand}" CommandParameter="{Binding ModuleName}" ...

使用演员表取出它 - 假设它是一个字符串:

private void LaunchCommandExecute(object parameter){
    string moduleName = parameter as string;
    // ...
}

(请注意,您也可以使用CommandParameter{Binding RelativeSource={RelativeSource Self},Path=Tag}设置为按钮的标记或内容,但在这种情况下,这将是一种全面的方法。)