Jitendra singh
Jitendra singh

Reputation: 433

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

Hi am using button click event in xaml file :

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

I am using button click event in xaml.cs file :

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

    }

This is my relay command :

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

Upvotes: 1

Views: 1210

Answers (1)

Saidi oussama
Saidi oussama

Reputation: 19

try this

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

 }

or use eventtocommand of mvvmlight toolkit,

but with controls which have command property button and checkbox for example you have just to bind your RelayCommand to the command property

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

Upvotes: 2

Related Questions