wpf 通过CallMethodAction来调用ViewModel里面的事件方法

1 新建wpf应用

2 通过nuget导入Microsoft.xaml.Behaviors库

3 新建ViewModels文件夹,并创建MainViewModel类

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Input;
using WpfApp3.Base;

namespace WpfApp3.ViewModels
{
    public class MainViewModel
    {

       
    }
}

 4 为Border添加MouseLeftButtonDown事件

<Window x:Class="WpfApp3.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:local="clr-namespace:WpfApp3"
        xmlns:behaviour="http://schemas.microsoft.com/xaml/behaviors"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="800">
    <Grid>
        <Border Width="100" Height=" 30" Background="Orange" MouseLeftButtonDown="Border_MouseLeftButtonDown" >
           
        </Border>
    </Grid>
</Window>

5 将xaml中的MouseLeftButtonDown事件方法拷贝到MainViewModel中,并将private修饰符改为public

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Input;
using WpfApp3.Base;

namespace WpfApp3.ViewModels
{
    public class MainViewModel
    {

        public void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {

        }
    }
}

6 修改MainWindow.xaml文件,添加触发器,这里TargetObject属性设置为{Binding},就会把向上查找最近的DataContext赋值给该属性,然后就会调用DataContext里面的对应MethodName方法

<Window x:Class="WpfApp3.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:local="clr-namespace:WpfApp3"
        xmlns:behaviour="http://schemas.microsoft.com/xaml/behaviors"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="800">
    <Grid>
        <Border Width="100" Height=" 30" Background="Orange">
            <behaviour:Interaction.Triggers>
                <behaviour:EventTrigger EventName="MouseLeftButtonDown">
                    <behaviour:CallMethodAction TargetObject="{Binding}" MethodName="Border_MouseLeftButtonDown" />
                </behaviour:EventTrigger>
            </behaviour:Interaction.Triggers>
        </Border>
    </Grid>
</Window>

7 运行,既可以调用MainViewModel中的事件方法

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值