弹出由DataTrigger触发

时间:2016-02-24 10:28:40

标签: c# wpf xaml popup datatrigger

我正在尝试根据我的ViewModel中的数据更改打开弹出窗口:

Popup定义如下:

 <Popup x:Name="popup"
AllowsTransparency="True"
Focusable="False"
IsHitTestVisible="False"
Placement="Bottom"
PopupAnimation="Slide"
StaysOpen="False">... </Popup>

我有用户控制

<UserControl>
 ...
<ControlTemplate>
  <ControlTemplate.Triggers>
     <DataTrigger Binding="{Binding PopupOpened}" Value="True">
         <DataTrigger.EnterActions>
             <BeginStoryboard Storyboard="{StaticResource ShowPopup}"/>
         </DataTrigger.EnterActions>
     </DataTrigger>
  </ControlTemplate.Triggers>
</ControlTemplate>
</UserControl>

我的动画定义为(在资源中):

 <Storyboard x:Key="ShowPopup">
 <BooleanAnimationUsingKeyFrames Storyboard.TargetName="popup" Storyboard.TargetProperty="(Popup.IsOpen)">
                    <DiscreteBooleanKeyFrame KeyTime="00:00:00.00" Value="True" />
                </BooleanAnimationUsingKeyFrames>
            </Storyboard>

如果我在某些控件的触发器(例如按钮)上从EventTrigger触发此动画,则它可以正常工作。

它在DataTrigger中无法正常工作。

编辑:

我发现了一个问题: 如果使用Animation +绑定控制Popup.IsOpen属性,则绑定到该属性将仅适用于您将使用动画更改该属性。之后,Binding将不再起作用。因此,您必须始终通过动画更改IsOpen属性或绑定不混合!

1 个答案:

答案 0 :(得分:0)

您的示例中有几个错误会掩盖真正的问题。 您的DataTrigger元素未关闭,并且&#39; StaticResources&#39;应该是StaticResource

但最终,UserControl的模板未正确使用,您错过了UserControl.Template设置。如果我们修复它,我们会看到异常:

<UserControl>
    <UserControl.Template>
        <ControlTemplate>
            <ControlTemplate.Triggers>
                <DataTrigger Binding="{Binding PopupOpened}" Value="True">
                    <DataTrigger.EnterActions>
                        <BeginStoryboard Storyboard="{StaticResource ShowPopup}" />
                    </DataTrigger.EnterActions>
                </DataTrigger>
            </ControlTemplate.Triggers>
            <!-- Some content for template to have substance -->
            <TextBlock />
        </ControlTemplate>
    </UserControl.Template>
</UserControl>

结果如下:

  

&#39;弹出&#39;在名称范围内找不到名称   &#39; System.Windows.Controls.ControlTemplate&#39;

实际执行此操作的最简单方法是IMO,它是一种简单的直接绑定:

<Popup x:Name="popup"
       IsOpen="{Binding PopupOpened, Mode=TwoWay}">

或者,如果您确实需要触发器,可以将其移动到Popup本身:

<Popup x:Name="popup">
    <Popup.Style>
        <Style>
            <Style.Triggers>
                <DataTrigger Binding="{Binding PopupOpened}" Value="True">
                    <DataTrigger.EnterActions>
                        <BeginStoryboard>
                            <Storyboard>
                                <BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="IsOpen">
                                    <DiscreteBooleanKeyFrame KeyTime="00:00:00.00" Value="True" />
                                </BooleanAnimationUsingKeyFrames>
                            </Storyboard>
                        </BeginStoryboard>
                    </DataTrigger.EnterActions>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Popup.Style>

    <TextBlock />
</Popup>