CANN/GE DataFlow构图接口参考(C++)
2026/6/20 17:02:20
当需要按钮在鼠标悬停时改变颜色,或者当用户在文本框中输入特定内容时自动执行某个操作。在传统的 WPF 开发中,可能需要编写大量的代码来处理事件(如MouseEnter、TextChanged)。虽然可行,但这会让XAML文件变得臃肿,或者增加后端代码文件的代码体量。
Microsoft.Xaml.Behaviors提供了一种更优雅、声明式的方式来处理这些交互逻辑。它的核心思想是“行为”(Behaviors)和“触发器”(Triggers)。
行为 (Behavior):可以将其看作是为一个控件(如Button、TextBox)添加的“附加功能”。
触发器 (Trigger):触发器负责“检测”某种条件是否满足(如事件发生、属性值改变、数据绑定完成)。
EventTrigger:当某个特定事件(如Click、MouseEnter)发生时触发。DataTrigger:当绑定的数据满足特定条件时触发。PropertyChangedTrigger:当某个依赖属性的值改变时触发。动作 (Action):动作定义了当触发器被激活时要执行的“操作”。
InvokeCommandAction:调用一个命令。ControlStoryboardAction:控制动画(开始、暂停、恢复、停止)。PlaySoundAction:播放声音。CallMethodAction:调用对象的一个方法。ChangePropertyAction:改变一个控件的属性值。Microsoft.Xaml.Behaviors.Wpf。xmlns:behaviors="http://schemas.microsoft.com/xaml/behaviors"(命名空间别名behaviors可以自定义,如b或i,但http://schemas.microsoft.com/xaml/behaviors是核心 URI,固定不变)
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"<ButtonContent="悬停此处变色"Width="100"Height="50"><i:Interaction.Triggers><i:EventTriggerEventName="MouseEnter"><i:ChangePropertyActionPropertyName="Background"Value="Red"/></i:EventTrigger><i:EventTriggerEventName="MouseLeave"><i:ChangePropertyActionPropertyName="Background"Value="Blue"/></i:EventTrigger></i:Interaction.Triggers></Button>Interaction.Triggers是一个附加属性,用于为控件(这里是Button)定义触发器集合。EventTrigger:MouseEnter事件,当鼠标进入按钮区域时,触发ChangePropertyAction。这个动作将按钮的Background属性改为红色。MouseLeave事件,当鼠标离开时,将背景色改回蓝色。2.点击按钮执行 ViewModel 的命令
MyCommand:publicclassMainViewModel{publicICommandMyCommand{get;set;}//使用RelayCommand或其他ICommand实现}<ButtonContent="点击执行命令"><i:Interaction.Triggers><i:EventTriggerEventName="Click"><i:InvokeCommandActionCommand="{Binding MyCommand}"/></i:EventTrigger></i:Interaction.Triggers></Button>Click事件。InvokeCommandAction会执行绑定的MyCommand命令。通常是在 ViewModel 中定义的业务逻辑。<BorderWidth="100"Height="100"Background="Green"><i:Interaction.Behaviors><i:MouseDragElementBehavior/></i:Interaction.Behaviors><TextBlockText="拖拽此处"VerticalAlignment="Center"HorizontalAlignment="Center"/></Border>Interaction.Behaviors是一个附加属性,用于为控件(这里是Border)定义行为集合。MouseDragElementBehavior行为。附加此行为后,用户就可以用鼠标按住Border并拖动它。行为内部处理了所有的鼠标事件和位置计算。Interaction.Triggers:用于托管触发器 (TriggerBase的子类)。Interaction.Behaviors:用于托管行为 (Behavior的子类)。EventTrigger,DataTrigger等)。InvokeCommandAction,ChangePropertyAction等)。MouseDragElementBehavior等)。