joh
joh

Reputation: 71

How do I call a call method from XAML in WPF?

How do I call a call method from XAML in WPF?

Upvotes: 7

Views: 14199

Answers (3)

Reed Copsey
Reed Copsey

Reputation: 564931

The typical way this is handled is by wrapping your method into an ICommand, and using the Commanding infrastructure in WPF.

I blogged about Commanding, showing some of the advantages of this approach, especially when you use something like the RelayCommand implementation in Josh Smith's MVVM article.

Upvotes: 6

chviLadislav
chviLadislav

Reputation: 1394

Except the commands there is another way that allows you to call a method directly from XAML. It is not commonly used but the option is still there.

The method must have one of the two types of signatures

  • void Foo()
  • void Bar(object sender, EventArgs e)

To make it working, you have to include references and namespaces of the Microsoft.Expression.Interactions and System.Windows.Interactivity into your project. Easiest way is to install a nuget. In the example below the namespaces are defined as xmlns:i and xmlns:ei.

<Window x:Class="Interactivity.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
    xmlns:local="clr-namespace:Interactivity"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Grid>
    <Button HorizontalAlignment="Center" VerticalAlignment="Center" Content="Run" IsEnabled="{Binding CanRun}">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Click">
                <ei:CallMethodAction MethodName="VoidParameterlessMethod" TargetObject="{Binding}" />
                <ei:CallMethodAction MethodName="EventHandlerLikeMethod" TargetObject="{Binding}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </Button>
</Grid>

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
    }

    public void VoidParameterlessMethod() 
        => Console.WriteLine("VoidParameterlessMethod called");

    public void EventHandlerLikeMethod(object o, EventArgs e) 
        => Console.WriteLine("EventHandlerLikeMethod called");

}

Upvotes: 2

Pradeep Yadav
Pradeep Yadav

Reputation: 93

You Can create RelayCommand inheriting ICommand, and then create property of ICommand and assign relay command to that property and call the method.

Upvotes: 0

Related Questions