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