【问题标题】:RoutedEvent TextBox.LostFocus not working in my WPF applicationRoutedEvent TextBox.LostFocus 在我的 WPF 应用程序中不起作用
【发布时间】:2018-02-06 17:35:43
【问题描述】:

我正在使用 Storyboard 处理 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"/>

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

谁能给我一些见解?

【问题讨论】:

    标签: wpf xaml storyboard eventtrigger


    【解决方案1】:

    您应该将触发器直接放在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 路由事件触发,因为这些事件的冒泡策略。

    【讨论】:

    • 感谢您的解决方案,对我来说就像一个魅力。 :D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-19
    • 2019-07-21
    • 2020-03-07
    • 1970-01-01
    相关资源
    最近更新 更多