WPF-数据触发器

放肆的年华 提交于 2019-11-29 23:33:37

触发器基本上使您能够更改属性值或根据属性值采取行动。因此,它允许您动态地更改控件的外观和/或行为,而无需创建新的控件。
当满足某些条件时,触发器用于更改任何给定属性的值。触发器通常在应用于特定控件的样式或文档根中定义。有三种类型的触发器
• 属性触发器
• 数据触发器
• 事件触发器

数据触发器
当绑定数据满足某些条件时,数据触发器执行某些操作。让我们看看下面的XAML代码,其中创建了一个带有一些属性的复选框和文本块。选中该复选框时,它将将其前景色更改为红色。

<Window x:Class="trigger.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:trigger"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel HorizontalAlignment = "Center">
        <CheckBox x:Name = "redColorCheckBox" 
            Content = "Set red as foreground color" Margin = "20"/>
        <TextBlock Name = "txtblock" VerticalAlignment = "Center" 
            Text = "Event Trigger" FontSize = "24" Margin = "20">
            <TextBlock.Style>
                <Style>
                    <Style.Triggers>
                        <DataTrigger Binding = "{Binding ElementName = redColorCheckBox, Path = IsChecked}" 
                        Value = "true">
                            <Setter Property = "TextBlock.Foreground" Value = "Red"/>
                            <Setter Property = "TextBlock.Cursor" Value = "Hand" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </TextBlock.Style>
        </TextBlock>
    </StackPanel>
</Window>

执行上述代码时,它将产生以下窗口:
在这里插入图片描述
勾选该复选框后,文本块的前景色将变为红色。
在这里插入图片描述

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!