行为库
介绍

安装与使用

安装

行为库的 NuGet 包名为 Microsoft.Xaml.Behaviors.Wpf。你可以借助 dotnet CLI 或者 Visual Studio 等 IDE 的 NuGet 包管理器来搜索并安装它。

dotnet add package Microsoft.Xaml.Behaviors.Wpf

使用

安装完毕后,我们就可以使用它了。下面是一个简单的例子:

MainWindow.xaml
<Window x:Class="WpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Content="Click Me">
            <i:Interaction.Triggers> 
                <i:EventTrigger EventName="Click"> 
                    <i:InvokeCommandAction Command="{Binding ClickCommand}" /> 
                </i:EventTrigger> 
            </i:Interaction.Triggers> 
        </Button>
    </Grid>
</Window>

提示

官方从最近几个版本开始,默认的命名空间前缀是 b。但笔者的建议是使用 i 作为前缀。因为我们在使用它时,几乎总是以访问 Interaction 下的附加属性开始,并且早期的命名空间也是 i。不仅如此,通常我们在开发中还会额外实现一些自定义的行为。此时,我们可以将自己的命名空间前缀设置为 b,这样就不会与官方的命名空间冲突了。

On this page