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

XML 复制代码
<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有参数时,参数添加示例如下:

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

Behavior添加注意事项:

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

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

XML 复制代码
 <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的源码及更加详尽的介绍。

相关推荐
神仙别闹9 分钟前
基于C#+SQL Server实现(Web)学生选课管理系统
前端·数据库·c#
向宇it1 小时前
【unity组件介绍】URP Decal Projector贴花投影器,将特定材质(贴花)投影到场景中的其他对象上。
游戏·3d·unity·c#·游戏引擎·材质
斯是 陋室10 小时前
在CentOS7.9服务器上安装.NET 8.0 SDK
运维·服务器·开发语言·c++·c#·云计算·.net
inwith12 小时前
C#语法基础总结(超级全面)(二)
开发语言·c#
ヾChen15 小时前
13届蓝桥杯省赛程序设计试题
物联网·学习·蓝桥杯·c#
我是唐青枫20 小时前
C#.NET 泛型详解
开发语言·c#·.net
Yasin Chen20 小时前
C# StringBuilder源码分析
开发语言·c#
格林威21 小时前
Baumer工业相机堡盟工业相机如何通过YoloV8模型实现人物识别(C#)
开发语言·人工智能·数码相机·yolo·计算机视觉·c#
Rabbb1 天前
C# JSON 反序列化时,忽略转换失败的属性 JTokenSafeToExtensions
后端·c#·json
三目条件1 天前
C#将类属性保存到Ini文件方法(利用拓展方法,反射方式获取到分组名和属性名称属性值)
java·开发语言·c#