【问题标题】:How do I call a call method from XAML in WPF?如何在 WPF 中从 XAML 调用调用方法?
【发布时间】:2010-02-02 17:59:05
【问题描述】:

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

【问题讨论】:

    标签: wpf xaml


    【解决方案1】:

    处理这种情况的典型方法是将您的方法包装到 ICommand 中,并使用 Commanding infrastructure in WPF

    blogged about Commanding,展示了这种方法的一些优点,尤其是当您使用类似Josh Smith's MVVM article 中的 RelayCommand 实现时。

    【讨论】:

    • 请注意,使用命令基础结构仅执行用户交互的方法。否则请阅读 xaml 触发器。
    【解决方案2】:

    除了命令之外,还有另一种方法可以让您直接从 XAML 调用方法。它不常用,但选项仍然存在。

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

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

    要使其正常工作,您必须将Microsoft.Expression.InteractionsSystem.Windows.Interactivity 的引用和命名空间包含到您的项目中。最简单的方法是安装nuget. 在下面的示例中,命名空间定义为xmlns:ixmlns: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");
    
    }
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-15
        • 2021-02-06
        • 2011-10-28
        • 2013-04-27
        • 1970-01-01
        • 1970-01-01
        • 2013-04-25
        • 1970-01-01
        相关资源
        最近更新 更多