WPF 事件转命令

复制代码
<Window x:Class="WpfAppDemo.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:WpfAppDemo" 
        xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
        xmlns:ViewModel="clr-namespace:WpfAppDemo.ViewModel" 
        mc:Ignorable="d"
        Title="MainWindow"
        Height="450" Width="800">
    <Window.DataContext>
        <ViewModel:MainViewModel/>
    </Window.DataContext>
    <Grid>
        <Image Source="https://www.toopic.cn/public/uploads/small/1642751451645164275145189.jpg">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="MouseUp">
                    <i:InvokeCommandAction Command="{Binding MouseUpCommand}" CommandParameter="ImageMouseUp"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </Image>
    </Grid>
</Window>
复制代码

 ViewModel:

复制代码
public class MainViewModel
{
    public ICommand MouseUpCommand
    {
        get => new RelayCommand<string>(ImageMouseUp);
    }

    private void ImageMouseUp(string str)
    {
        MessageBox.Show(str);
    }
}            
复制代码

 

  • 下载程序安装包  Microsoft.Xaml.Behaviors.Wpf 

 

  • 添加引用:xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
  • 在需要转命令的控件添加:
<i:Interaction.Triggers>
    <i:EventTrigger EventName="MouseUp【需要的事件】">
        <i:InvokeCommandAction Command="{Binding 【命令】}" CommandParameter="传递的参数"/>
    </i:EventTrigger>
</i:Interaction.Triggers>

  • 效果:

 

posted @   lxiamul  阅读(353)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示