当前位置: 首页 > news >正文

WINUI——Behavior(行为)小结

前言

在使用MVVM进行WINUI或WPF开发时,Command在某些时候并不能满足逻辑与UI分离的要求。这时肯定就需要其它技术的支持,Behavior就是一种。在WPF中是有Behavior直接支持的,转到WINUI后,相对有一些麻烦,于是在此记录之,以备忘。

开发环境

WIN11

VS2022

Nuget包:Microsoft.Xaml.Behaviors.WinUI.Managed

如何使用Behavior?

1. 首先安装Microsoft.Xaml.Behaviors.WinUI.Managed

当前(2024/6/6)的最新版本为2.0.9。

2. 在需要使用的Page引用InteractivityInteractions

    xmlns:Interactivity="using:Microsoft.Xaml.Interactivity"
    xmlns:Interactions="using:Microsoft.Xaml.Interactions.Core"

3. 在需要的控件添加相应的Behavior

以下以InvokeCommandAction(即是调用VM中的Command)为示例,更多详细操作可参见Github相应文档,链接为:InvokeCommandAction · microsoft/XamlBehaviors Wiki · GitHub

<Button x:Name="button1"><Interactivity:Interaction.Behaviors><Interactions:EventTriggerBehavior EventName="Click" SourceObject="{Binding ElementName=button1}"><Interactions:InvokeCommandAction Command="{Binding UpdateCountCommand}"/></Interactions:EventTriggerBehavior></Interactivity:Interaction.Behaviors>
</Button>

若调用的Command有参数时,参数添加示例如下:

<Interactions:InvokeCommandAction Command="{x:Bind ViewModel.UserNameChangedCommand}" 
CommandParameter="{Binding ElementName=UserNameTextBox, Path=Text}" />

Behavior添加注意事项:

若有参数时,请一定要在控件的Content内添加Behavior,不可将它的Behavior添加到集中管理的Behaviors中。

如将UserNameTextBox的Behavior添加到下述的Behaviors,那么它的的参数CommandParameter可能就会获取不到。

 <Interactivity:Interaction.Behaviors><Interactions:EventTriggerBehavior EventName="TextChanged" SourceObject="{Binding ElementName=UserNameTextBox}"><Interactions:InvokeCommandAction Command="{Binding UserNameChangedCommand}" CommandParameter="{Binding ElementName=UserNameTextBox, Path=Text}" /></Interactions:EventTriggerBehavior><Interactions:EventTriggerBehavior EventName="Load" SourceObject="{Binding ElementName=TestPage}"><Interactions:InvokeCommandAction Command="{Binding PageLoadCommand}"/></Interactions:EventTriggerBehavior></Interactivity:Interaction.Behaviors>

原因可能是集中管理的Behaviors在所在层的可视化树上找不到UserNameTextBox这个SourceObject,于是就不能正确获取到它的文本。此后续弄清原因再做更新……

参考链接:

GitHub - microsoft/XamlBehaviors: This is the official home for UWP XAML Behaviors on GitHub.

以上链接为XamlBehaviors的仓库地址,及引入Microsoft.Xaml.Behaviors.WinUI.Managed的源码及更加详尽的介绍。

http://www.lryc.cn/news/368581.html

相关文章:

  • Ruoyi5.x RuoYi-Vue-Plus新建Translation翻译类
  • 类加载的奥秘
  • Spring知识点总结
  • STM32Cube系列教程11:STM32 AES加解密模块性能测试
  • Vue2基础:.sync修饰符的使用,认识,作用,本质案例演示,实现父子之间的通信。
  • 【数据结构与算法】使用单链表实现队列:原理、步骤与应用
  • DHCP服务
  • C++笔试-剑指offer
  • Mac安装jadx并配置环境
  • 前端学习----css基础语法
  • 超详解——python条件和循环——小白篇
  • DNS协议 | NAT技术 | 代理服务器
  • 深入ES6:解锁 JavaScript 类与继承的高级玩法
  • 领域驱动设计:异常处理
  • 网络网络层之(6)ICMPv6协议
  • 《大道平渊》· 拾壹 —— 商业一定是个故事:讲好故事,员工奋发,顾客买单。
  • JavaScript 如何访问本地文件夹
  • ArrayList顺序表简单实现
  • 144、二叉树的前序递归遍历
  • youtube 1080 分辨率 下载方式
  • 计算机网络ppt和课后题总结(下)
  • 测试基础12:测试用例设计方法-边界值分析
  • AI大模型在健康睡眠监测中的深度融合与实践案例
  • 【西瓜书】9.聚类
  • 使用jemalloc实现信号驱动的程序堆栈信息打印
  • 树的4种遍历
  • 深入探讨5种单例模式
  • SPOOL
  • 挑战绝对不可能:再证有长度不同的射线
  • 【机器学习】Python与深度学习的完美结合——深度学习在医学影像诊断中的惊人表现