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中的事件方法