如何给出EventTrigger的条件?

时间:2010-05-04 10:17:11

标签: wpf

是否可以在EventTrigger中提供条件?我为Radio按钮编写了一个以下EventTrigger(Mouse.MouseLeave)。我希望不应该触发处于Checked条件(IsChecked = True)的项目。

<EventTrigger RoutedEvent="Mouse.MouseLeave" SourceName="border">                                 
      <BeginStoryboard Name="out_BeginStoryboard" Storyboard="{StaticResource out}" />
      <RemoveStoryboard BeginStoryboardName="over_BeginStoryboard" />
</EventTrigger>

请让我知道如何实现这一目标?

提前致谢。

6 个答案:

答案 0 :(得分:22)

您不能以这种方式使用EventTrigger。调用EventTriggers的WPF的RoutedEventHandler没有提供任何使触发器成为条件的机制,你不能通过继承TriggerAction来解决这个问题,因为没有受保护的Invoke()或Execute()操作要覆盖。

但是,使用自定义类可以非常轻松地完成此操作。以下是它的使用方法:

<Border>
  <my:ConditionalEventTrigger.Triggers>
    <my:ConditionalEventTriggerCollection>
      <my:ConditionalEventTrigger RoutedEvent="Mouse.MouseLeave"
                                  Condition="{Binding IsChecked, ElementName=checkbox}">
        <BeginStoryboard Name="out_BeginStoryboard" Storyboard="{StaticResource out}" />               
        <RemoveStoryboard BeginStoryboardName="over_BeginStoryboard" />               
      </my:ConditionalEventTrigger>               
    </my:ConditionalEventTriggerCollection>
  </my:ConditionalEventTrigger.Triggers>
  ...

以下是如何实施的:

[ContentProperty("Actions")] 
public class ConditionalEventTrigger : FrameworkContentElement
{ 
  public RoutedEvent RoutedEvent { get; set; } 
  public List<TriggerAction> Actions { get; set; }

  // Condition
  public bool Condition { get { return (bool)GetValue(ConditionProperty); } set { SetValue(ConditionProperty, value); } }
  public static readonly DependencyProperty ConditionProperty = DependencyProperty.Register("Condition", typeof(bool), typeof(ConditionalEventTrigger));

  // "Triggers" attached property
  public static ConditionalEventTriggerCollection GetTriggers(DependencyObject obj) { return (ConditionalEventTriggerCollection)obj.GetValue(TriggersProperty); }
  public static void SetTriggers(DependencyObject obj, ConditionalEventTriggerCollection value) { obj.SetValue(TriggersProperty, value); }
  public static readonly DependencyProperty TriggersProperty = DependencyProperty.RegisterAttached("Triggers", typeof(ConditionalEventTriggerCollection), typeof(ConditionalEventTrigger), new PropertyMetadata 
  { 
    PropertyChangedCallback = (obj, e) => 
    { 
      // When "Triggers" is set, register handlers for each trigger in the list 
      var element = (FrameworkElement)obj; 
      var triggers = (List<ConditionalEventTrigger>)e.NewValue;
      foreach(var trigger in triggers)
        element.AddHandler(trigger.RoutedEvent, new RoutedEventHandler((obj2, e2) =>
          trigger.OnRoutedEvent(element)));
    } 
  });

  public ConditionalEventTrigger()
  {
    Actions = new List<TriggerAction>();
  }

  // When an event fires, check the condition and if it is true fire the actions 
  void OnRoutedEvent(FrameworkElement element) 
  { 
    DataContext = element.DataContext;  // Allow data binding to access element properties
    if(Condition) 
    { 
      // Construct an EventTrigger containing the actions, then trigger it 
      var dummyTrigger = new EventTrigger { RoutedEvent = _triggerActionsEvent }; 
      foreach(var action in Actions) 
        dummyTrigger.Actions.Add(action); 

      element.Triggers.Add(dummyTrigger); 
      try 
      { 
        element.RaiseEvent(new RoutedEventArgs(_triggerActionsEvent)); 
      } 
      finally 
      { 
        element.Triggers.Remove(dummyTrigger); 
      } 
    } 
  } 

  static RoutedEvent _triggerActionsEvent = EventManager.RegisterRoutedEvent("", RoutingStrategy.Direct, typeof(EventHandler), typeof(ConditionalEventTrigger)); 

} 

// Create collection type visible to XAML - since it is attached we cannot construct it in code 
public class ConditionalEventTriggerCollection : List<ConditionalEventTrigger> {} 

享受!

答案 1 :(得分:8)

这对我有用......

我希望基于鼠标悬停在UI元素上并且UI元素的相关所有者处于活动状态(即启用以使玩家移动)来执行动画。

为了支持这些要求,我使用了相对源代码绑定来克服对事件触发条件缺乏支持。

示例:

<MultiDataTrigger>
    <MultiDataTrigger.Conditions>
        <Condition Binding="{Binding RelativeSource={RelativeSource self}, Path=IsMouseOver}" Value="True" />
        <Condition Binding="{Binding Path=IsPlayer1Active}" Value="True" />
    </MultiDataTrigger.Conditions>
    <MultiDataTrigger.EnterActions>
        <BeginStoryboard>
            <Storyboard>
                <ColorAnimation Storyboard.TargetProperty="Background.GradientStops[0].Color" To="#FF585454" Duration="0:0:.25"/>
                <ColorAnimation Storyboard.TargetProperty="Background.GradientStops[1].Color" To="Black" Duration="0:0:2"/>
            </Storyboard>
        </BeginStoryboard>
    </MultiDataTrigger.EnterActions>
</MultiDataTrigger>

答案 2 :(得分:4)

这是我Ray's answer的修改版本,它只在设置源触发器时创建并附加虚拟事件,而不是每次都这样做。我认为这对我的场景会更好,因为我在数百个项目上筹集活动,而不仅仅是一两个:

[ContentProperty("Actions")]
public class ConditionalEventTrigger : FrameworkContentElement
{
    static readonly RoutedEvent DummyEvent = EventManager.RegisterRoutedEvent(
        "", RoutingStrategy.Direct, typeof(EventHandler), typeof(ConditionalEventTrigger));

    public static readonly DependencyProperty TriggersProperty = DependencyProperty.RegisterAttached(
        "Triggers", typeof(ConditionalEventTriggers), typeof(ConditionalEventTrigger),
        new FrameworkPropertyMetadata(RefreshTriggers));

    public static readonly DependencyProperty ConditionProperty = DependencyProperty.Register(
        "Condition", typeof(bool), typeof(ConditionalEventTrigger)); // the Condition is evaluated whenever an event fires

    public ConditionalEventTrigger()
    {
        Actions = new List<TriggerAction>();
    }

    public static ConditionalEventTriggers GetTriggers(DependencyObject obj)
    { return (ConditionalEventTriggers)obj.GetValue(TriggersProperty); }

    public static void SetTriggers(DependencyObject obj, ConditionalEventTriggers value)
    { obj.SetValue(TriggersProperty, value); }

    public bool Condition
    {
        get { return (bool)GetValue(ConditionProperty); }
        set { SetValue(ConditionProperty, value); }
    }

    public RoutedEvent RoutedEvent { get; set; }
    public List<TriggerAction> Actions { get; set; }

    // --- impl ----

    // we can't actually fire triggers because WPF won't let us (stupid sealed internal methods)
    // so, for each trigger, make a dummy trigger (on a dummy event) with the same actions as the real trigger,
    // then attach handlers for the dummy event
    public static void RefreshTriggers(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        var targetObj = (FrameworkElement)obj;
        // start by clearing away the old triggers
        foreach (var t in targetObj.Triggers.OfType<DummyEventTrigger>().ToArray())
            targetObj.Triggers.Remove(t);

        // create and add dummy triggers
        foreach (var t in ConditionalEventTrigger.GetTriggers(targetObj))
        {
            t.DataContext = targetObj.DataContext; // set and Track DataContext so binding works
            // targetObj.GetDataContextChanged().WeakSubscribe(dc => t.DataContext = targetObj.DataContext);

            var dummyTrigger = new DummyEventTrigger { RoutedEvent = DummyEvent };
            foreach (var action in t.Actions)
                dummyTrigger.Actions.Add(action);

            targetObj.Triggers.Add(dummyTrigger);
            targetObj.AddHandler(t.RoutedEvent, new RoutedEventHandler((o, args) => {
                if (t.Condition) // evaluate condition when the event gets fired
                    targetObj.RaiseEvent(new RoutedEventArgs(DummyEvent));
            }));
        }
    }

    class DummyEventTrigger : EventTrigger { }
}

public class ConditionalEventTriggers : List<ConditionalEventTrigger> { }

它的使用方式如下:

<Border>
  <local:ConditionalEventTrigger.Triggers>
    <local:ConditionalEventTriggers>
      <local:ConditionalEventTrigger RoutedEvent="local:ClientEvents.Flash" Condition="{Binding IsFlashing}">
        <BeginStoryboard Name="FlashAnimation">...

该行

// targetObj.GetDataContextChanged().WeakSubscribe(dc => t.DataContext = targetObj.DataContext);

正在使用我写的反应式框架和一些扩展方法,基本上我们需要订阅目标对象的.DataContextChanged事件,但我们需要使用弱引用。如果你的对象没有改变他们的datacontext,那么你根本就不需要这个代码

答案 3 :(得分:0)

在您的情况下,您需要:

<EventTrigger RoutedEvent="Checked" SourceName="border">

编辑: 根据您的意见,您正在寻找一个多重触发器。

   <MultiDataTrigger>
        <MultiDataTrigger.Conditions>
            <Condition SourceName="border" Property="IsMouseOver" Value="false" />                                            
        </MultiDataTrigger.Conditions>
        <MultiDataTrigger.EnterActions>
            <BeginStoryboard Name="out_BeginStoryboard" Storyboard="{StaticResource out}" />
            <RemoveStoryboard BeginStoryboardName="over_BeginStoryboard" />
        </MultiDataTrigger.EnterActions>
   </MultiDataTrigger>

答案 4 :(得分:0)

我知道这是一篇很老的帖子,但是当我最终找到答案时,这里的内容对我有用。基本上我想要一个面板在鼠标悬停时从屏幕右侧动画,然后在鼠标离开时返回。但是,只有当面板没有固定时。我的ViewModel上存在IsShoppingCartPinned属性。就您的方案而言,您可以使用复选框IsShoppingCartPinned属性替换IsChecked属性,并在EventTriggers上运行任何类型的动画。

以下是代码:

<Grid.Style>
     <Style TargetType="{x:Type Grid}">
          <Setter Property="Margin" Value="0,20,-400,20"/>
          <Setter Property="Grid.Column" Value="0"/>
          <Style.Triggers>
               <MultiDataTrigger>
                    <MultiDataTrigger.Conditions>
                         <Condition Binding="{Binding IsShoppingCartPinned}" Value="False"/>
                         <Condition Binding="{Binding RelativeSource={RelativeSource Self}, Path=IsMouseOver}" Value="True"/>
                    </MultiDataTrigger.Conditions>
                    <MultiDataTrigger.EnterActions>
                         <BeginStoryboard Name="ExpandPanel">
                              <Storyboard>
                                   <ThicknessAnimation Duration="0:0:0.1" Storyboard.TargetProperty="Margin" To="0,20,0,20"/>
                              </Storyboard>
                         </BeginStoryboard>
                    </MultiDataTrigger.EnterActions>
                    <MultiDataTrigger.ExitActions>
                         <BeginStoryboard Name="HidePanel">
                              <Storyboard>
                                   <ThicknessAnimation Duration="0:0:0.1" Storyboard.TargetProperty="Margin" To="0,20,-400,20"/>
                              </Storyboard>
                         </BeginStoryboard>
                    </MultiDataTrigger.ExitActions>
               </MultiDataTrigger>
               <DataTrigger Binding="{Binding IsShoppingCartPinned}" Value="True">
                    <DataTrigger.EnterActions>
                         <RemoveStoryboard BeginStoryboardName="ExpandPanel"/>
                         <RemoveStoryboard BeginStoryboardName="HidePanel"/>
                    </DataTrigger.EnterActions>
                    <DataTrigger.Setters>
                         <Setter Property="Margin" Value="0"/>
                         <Setter Property="Grid.Column" Value="1"/>
                    </DataTrigger.Setters>
               </DataTrigger>
          </Style.Triggers>
     </Style>
</Grid.Style>

答案 5 :(得分:0)

基于 Ray 和 Orion,这是我的版本,目标是您可以将 2 个触发器绑定到一个按钮,并在单击时翻转状态(或者更多状态,如果您愿意,它应该适用于所有控件)。当您绑定 ConditionProperty 时,必须将 ConditionValue 写为 False 表示 True,Ture 表示 False,这有点棘手。我猜这是因为在更新绑定之前执行了按钮的事件处理程序。它是这样使用的:

<Button x:Name="HoldButton" Content="{Binding Status.Running}"/>
    <mut:ConditionalEventTrigger.ConditionTriggers>
        <mut:ConditionalEventTriggers>
            <mut:ConditionalEventTrigger RoutedEvent="ButtonBase.Click" ConditionProperty="{Binding Status.Running}" ConditionValue="False">
                <BeginStoryboard x:Name="OnHold_BeginStoryboard" Storyboard="{StaticResource OnHold}"/>
            </mut:ConditionalEventTrigger>
            <mut:ConditionalEventTrigger RoutedEvent="ButtonBase.Click" ConditionProperty="{Binding Status.Running}" ConditionValue="True">
                <StopStoryboard BeginStoryboardName="OnHold_BeginStoryboard"/>
            </mut:ConditionalEventTrigger>
        </mut:ConditionalEventTriggers>
    </mut:ConditionalEventTrigger.ConditionTriggers>
</Button>

代码如下:

using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Markup;

namespace MyUtility.Trigger
{
    [ContentProperty("Actions")]
    public class ConditionalEventTrigger : FrameworkContentElement
    {
        public static readonly DependencyProperty ConditionTriggersProperty = DependencyProperty.RegisterAttached(
            "ConditionTriggers",
            typeof(ConditionalEventTriggers),
            typeof(ConditionalEventTrigger),
            new FrameworkPropertyMetadata(OnConditionalEventTriggersChanged));

        public static ConditionalEventTriggers GetConditionTriggers(FrameworkElement element)
        {
            return (ConditionalEventTriggers)element.GetValue(ConditionTriggersProperty);
        }

        public static void SetConditionTriggers(FrameworkElement element, List<ConditionalEventTrigger> value)
        {
            element.SetValue(ConditionTriggersProperty, value);
        }

        public static readonly DependencyProperty ConditionPropertyProperty = DependencyProperty.Register(
            "ConditionProperty",
            typeof(bool),
            typeof(ConditionalEventTrigger));

        public bool ConditionProperty
        {
            get
            {
                return (bool)GetValue(ConditionPropertyProperty);
            }
            set
            {
                SetValue(ConditionPropertyProperty, value);
            }
        }

        public static readonly DependencyProperty ConditionValueProperty = DependencyProperty.Register(
            "ConditionValue",
            typeof(bool),
            typeof(ConditionalEventTrigger));

        public bool ConditionValue
        {
            get
            {
                return (bool)GetValue(ConditionValueProperty);
            }
            set
            {
                SetValue(ConditionValueProperty, value);
            }
        }

        private static readonly RoutedEvent m_DummyEvent = EventManager.RegisterRoutedEvent(
            "ConditionalEventTriggerDummyEvent",
            RoutingStrategy.Direct,
            typeof(EventHandler),
            typeof(ConditionalEventTrigger));

        public RoutedEvent RoutedEvent { get; set; }
        public List<TriggerAction> Actions { get; set; }

        public ConditionalEventTrigger()
        {
            Actions = new List<TriggerAction>();
        }

        public static void OnConditionalEventTriggersChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            var element = (FrameworkElement)obj;
            var triggers = (ConditionalEventTriggers)e.NewValue;
            foreach(ConditionalEventTrigger t in triggers)
            {
                element.RemoveHandler(t.RoutedEvent, new RoutedEventHandler((obj2, e2) => t.OnRoutedEvent(element)));
                element.AddHandler(t.RoutedEvent, new RoutedEventHandler((obj2, e2) => t.OnRoutedEvent(element)));
            }
        }

        public void OnRoutedEvent(FrameworkElement element)
        {
            this.DataContext = element.DataContext;
            if (this.ConditionProperty == this.ConditionValue)
            {
                // .Net doesn't allow us fire a trigger directly, so we bingd trigger on Element and then fire the element.
                var dummyTrigger = new EventTrigger { RoutedEvent = m_DummyEvent };

                foreach (TriggerAction action in this.Actions)
                {
                    dummyTrigger.Actions.Add(action);
                }

                element.Triggers.Add(dummyTrigger);

                try
                {
                    element.RaiseEvent(new RoutedEventArgs(m_DummyEvent));
                }
                finally
                {
                    element.Triggers.Remove(dummyTrigger);
                }
            }
        }
    }

    public class ConditionalEventTriggers : List<ConditionalEventTrigger> {}
}