如何在WPF中从XAML调用调用方法?

如何在WPF中从XAML调用调用方法?,wpf,xaml,Wpf,Xaml,如何在WPF中从XAML调用调用方法?处理此问题的典型方法是将方法包装到,然后使用 I,展示了这种方法的一些优点,特别是当您使用中的RelayCommand实现时。您可以创建继承ICommand的RelayCommand,然后创建ICommand的属性,将relay命令分配给该属性并调用该方法。除了这些命令之外,还有另一种方法允许您直接从XAML调用方法。它不是常用的,但选项仍然存在 该方法必须具有两种类型的签名之一 void Foo() 空栏(对象发送器、事件参数) 要使其正常工作,您必须

如何在WPF中从XAML调用调用方法?

处理此问题的典型方法是将方法包装到,然后使用


I,展示了这种方法的一些优点,特别是当您使用中的RelayCommand实现时。

您可以创建继承ICommand的RelayCommand,然后创建ICommand的属性,将relay命令分配给该属性并调用该方法。

除了这些命令之外,还有另一种方法允许您直接从XAML调用方法。它不是常用的,但选项仍然存在

该方法必须具有两种类型的签名之一

  • void Foo()
  • 空栏(对象发送器、事件参数)
要使其正常工作,您必须在项目中包含
Microsoft.Expression.Interactions
System.Windows.Interactivity
的引用和名称空间。最简单的方法是在下面的示例中安装,名称空间定义为
xmlns:i
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>

请注意,使用命令基础结构仅在用户交互时执行方法。否则,请阅读xaml触发器。
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");

}