繁体   English   中英

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

[英]How to bind or execute relaycommand in Wpf from button click event in C#

嗨,我在xaml文件中使用按钮单击事件:

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

尝试这个

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM