RoutedEvent TextBox.LostFocus 在我的 WPF 应用程序中不起作用

RoutedEvent TextBox.LostFocus not working in my WPF application

我正在使用故事板处理 WPF 动画。我想要的是在我的文本框获得焦点后立即淡出页面的所有内容,并在焦点从文本框移开后立即淡入所有内容。为此,我有以下 XAML,没有任何代码。

<Page.Triggers>
  <EventTrigger RoutedEvent="TextBox.GotFocus">
     <BeginStoryboard>
        <Storyboard>
           <DoubleAnimation
              Storyboard.TargetName="Grid1"
              Storyboard.TargetProperty="Opacity"
              From="1" To="0.1" Duration="0:0:0.2"
              AutoReverse="False" >
           </DoubleAnimation>
        </Storyboard>
     </BeginStoryboard>
  </EventTrigger>
  <EventTrigger RoutedEvent="TextBox.LostFocus">
     <BeginStoryboard>
        <Storyboard>
           <DoubleAnimation
              Storyboard.TargetName="Grid1"
              Storyboard.TargetProperty="Opacity"
              From="0.1" To="1" Duration="0:0:0.2"
              AutoReverse="False">
           </DoubleAnimation>
        </Storyboard>
     </BeginStoryboard>
  </EventTrigger>

要将焦点移出文本框,我有以下按钮:

<Button
        Name="SearchButton" 
        Height="30" Width="30"
        Grid.Column="1"
        Focusable="True"
        IsHitTestVisible="True"
        Style="{StaticResource SearchButton}"
        Padding="3,3,3,3"
        Margin="3,3,3,3" Click="Button_Click"/>

当我 运行 应用程序时,单击文本框可以使淡出正常工作。但是当我点击按钮时,淡入没有开始。

谁能给我一些见解?

您应该将触发器直接放在 TextBox 层,而不是 Page 层:

  <TextBox>
    <TextBox.Triggers>
      <EventTrigger RoutedEvent="TextBox.GotFocus">
        <BeginStoryboard>
          <Storyboard>
            <DoubleAnimation
               Storyboard.TargetName="Grid1"
               Storyboard.TargetProperty="Opacity"
               From="1" To="0.1" Duration="0:0:0.2"
               FillBehavior="HoldEnd">
            </DoubleAnimation>
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
      <EventTrigger RoutedEvent="TextBox.LostFocus">
        <BeginStoryboard>
          <Storyboard>
            <DoubleAnimation
               Storyboard.TargetName="Grid1"
               Storyboard.TargetProperty="Opacity"
               From="0.1" To="1" Duration="0:0:0.2"
               FillBehavior="Stop">
            </DoubleAnimation>
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
    </TextBox.Triggers>
  </TextBox>

否则,Page 上每个 UIElement 的每个 GotFocusLostFocus 路由事件都会触发故事板,因为这些事件的冒泡策略.