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

前端 未结 3 790

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

相关标签:
3条回答
  • 2020-12-19 10:37

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

    0 讨论(0)
  • 2020-12-19 10:45

    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.

    0 讨论(0)
  • 2020-12-19 10:45

    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");
    
    }
    
    0 讨论(0)
提交回复
热议问题