在WPF(XAML)

时间:2017-08-04 16:02:17

标签: wpf class xaml eventtrigger

我想要做的是当我点击一个页面内的“testButton”按钮时,触发一个位于MainWindow内Window.Resource内的Border内的事件。如果我从EventTrigger中删除SourceName =“testButton”它适用于每个按钮,我想要的只是使用该特定按钮。

<Window x:Class="test.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:test"
        mc:Ignorable="d">

   <Window.Resources>
        <Style TargetType="{x:Type local:mainWindow}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Window}">
                        <Border Padding="5">
                            <Border.Background>
                                <SolidColorBrush x:Name="bgBrush" Color="Transparent" />
                            </Border.Background>
                              <Border.Triggers>
                                <EventTrigger RoutedEvent="Button.Click" SourceName="testButton">
                                    <BeginStoryboard>
                                        <Storyboard>
                                            <ColorAnimation
                                                        Storyboard.TargetName="bgBrush"
                                                        Storyboard.TargetProperty = "Color"
                                                        From="Transparent"
                                                        To = "White"
                                                        Duration="0:0:01.00"/>
                                        </Storyboard>
                                     </BeginStoryboard>
                                 </EventTrigger>
                             </Border.Triggers>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
</Window>

这是按钮所在的页面:

<Page x:Class="test.testPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:local="clr-namespace:test"
      mc:Ignorable="d" Width="300" Height="200">

    <Grid>
        <Button x:Name="testButton" Height="20" Width="50" Content="Test"/>
    </Grid>
</Page>

1 个答案:

答案 0 :(得分:0)

我正在分享示例代码,在点击按钮时将您的MainWindow背景颜色更改为红色。它将帮助您理解路由事件。有不同的方法。我创建了一个自定义事件来实现此目的。这是您的代码https://drive.google.com/file/d/0B4bUNjAQRJpWSEpLV1JJeXQ4N1k/view?usp=sharing