如何在C#中通过按钮单击事件绑定或执行Wpf中的relaycommand

时间:2015-06-08 09:24:49

标签: c# wpf xaml

您正在使用xaml文件中的按钮点击事件:

uint16_t extractInt(uint16_t orig16BitWord, unsigned from, unsigned to) 
{
  unsigned mask = ( (1<<(to-from+1))-1) << from;
  return (orig16BitWord & mask) >> from;
}

我在xaml.cs文件中使用按钮点击事件:

   <Button Focusable="False" Click="btnAddhighlight"
                        Grid.Column="0" Width="37" Height="37" VerticalAlignment="Center" HorizontalAlignment="Center">
            <Image Stretch="None">
                <Image.Style>
                    <Style TargetType="{x:Type Image}">
                        <Setter Property="Source" Value="/Resources/Highlighter.png"/>
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding IsPressed, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}" Value="True">
                                <Setter Property="Source" Value="/Resources/Highlighter_pressed.png"/>
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </Image.Style>
            </Image>
        </Button>

这是我的接力命令:

   private void Button_Click_1(object sender, RoutedEventArgs e)
    {
//I want to call relay command from this code

    }

1 个答案:

答案 0 :(得分:2)

试试这个

 private void Button_Click_1(object sender, RoutedEventArgs e)
 {
    var vm = (yourViewModel)DataContext;
    vm.AddHighlight.Execute(null);

 }

或使用mvvmlight工具包的eventtocommand,

但是控件具有命令属性按钮和复选框 你只需要将你的RelayCommand绑定到命令属性

<Button Focusable="False" Command="{Binding YourCommand}"