wpf功能增强库:Microsoft.Xaml.Behaviors.Wpf
Microsoft.Xaml.Behaviors.Wpf对 WPF 的核心增强点可概括为 3 点:突破命令绑定限制:让任意控件的任意事件都能绑定 ViewModel 的命令,符合 MVVM,消除冗余后台代码。
提供内置实用行为:封装了拖拽、聚焦等常用功能,开箱即用,提升开发效率。
支持自定义行为封装:将通用 UI 功能抽离为可复用组件,减少重复代码,便于项目维护和扩展。
这个库是 WPF MVVM 开发中的必备工具,尤其在复杂项目中,能大幅提升代码的整洁性和可维护性。
下面举一个例子。
效果为:
启动程序,文本框显示「默认测试内容」。
用鼠标点击文本框的任意位置,文字会立即全选且稳定保持(背景高亮,无单独光标出现)。
此时可以直接输入新内容,会覆盖全选的文字(符合常规全选后的交互逻辑)。



MainWindow.xaml
<Window x:Class="WpfApp1.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:WpfApp1"
mc:Ignorable="d"
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
Title="Behaviors简单演示" Height="200" Width="400">
<Grid Margin="20">
<!-- 布局:文本框 + 清空按钮 -->
<StackPanel VerticalAlignment="Center" Margin="0,10,0,10">
<!-- 文本框:实现「获得焦点时自动全选所有内容」 -->
<TextBox x:Name="txtInput" Text="默认测试内容" FontSize="14" Height="35" Padding="5">
<i:Interaction.Triggers>
<i:EventTrigger EventName="PreviewMouseDown">
<!-- 直接用自定义Action,包含所有逻辑 -->
<local:StopEventAndSelectAllAction/>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
<!-- 按钮:实现「点击时清空文本框内容」(这部分代码完全正确,无需修改) -->
<Button Content="清空文本框" FontSize="14" Height="35" Width="150">
<!-- 给Button附加Triggers(触发器集合) -->
<i:Interaction.Triggers>
<!-- 事件触发器:绑定Button的Click事件 -->
<i:EventTrigger EventName="Click">
<!-- 事件触发后执行的动作:修改目标控件的属性(清空TextBox的Text) -->
<!-- 目标控件:上面的文本框 -->
<i:ChangePropertyAction
TargetObject="{Binding ElementName=txtInput}"
PropertyName="Text"
Value=""/>
<!-- 要修改的属性:Text -->
<!-- 要设置的属性值:空字符串 -->
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</StackPanel>
</Grid>
</Window>StopEventAction.cs
using Microsoft.Xaml.Behaviors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace WpfApp1
{
/// <summary>
/// 自定义Action:阻止鼠标事件+给TextBox赋焦+全选文字
/// </summary>
// 泛型指定为TextBox,直接关联到TextBox控件(更精准)
public class StopEventAndSelectAllAction : TriggerAction<TextBox>
{
protected override void Invoke(object parameter)
{
// 1. 阻止鼠标点击的默认行为(中断事件传递)
if (parameter is RoutedEventArgs routedEventArgs)
{
routedEventArgs.Handled = true;
}
// 2. 给当前关联的TextBox赋焦+全选(直接操作控件,无方法调用问题)
if (this.AssociatedObject != null)
{
this.AssociatedObject.Focus(); // 直接调用TextBox的Focus方法
this.AssociatedObject.SelectAll(); // 直接调用全选方法
}
}
}
}