如何从c#中的按钮单击事件在Wpf中绑定或执行继电器命令

本文关键字:Wpf 绑定 执行 命令 继电器 单击 按钮 事件 | 更新日期: 2023-09-27 17:54:21

我在xaml文件中使用button click事件:

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

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

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

我的中继命令:

        AddHighlight = new RelayCommand(() =>
        {
            int page = _pageNumber;
            SelectionInfo selection = _selection;
            Rect? selectedVilualInfo = null;
            if (_selection != null)
                selectedVilualInfo = ConvertPixelsToScreen(_selection.SelectedRect, CurrentZoom, _visualObject);
            ParentVM.HighlightVM.SelectedVilualInfo = selectedVilualInfo;
            ParentVM.HighlightVM.IsVisible = Visibility.Visible;
            var vm = (ParentVM.CurrentReadingVm as ReadingBookSingleVM);
            if (vm != null)
            {
                ParentVM.HighlightVM.ResetCurrentColor();
                vm.SaveHighlight(page, HighlightVM.SerializeColorToString(ParentVM.HighlightVM.CurrentColor.Color));
                vm.CancelSelection(page);
                Selection = null;
            }
        });

如何从c#中的按钮单击事件在Wpf中绑定或执行继电器命令

try this

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

或使用mvvmlight工具包的eventtocommand,

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

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