开发者

Can WPF trigger values persist beyond the trigger condition?

I have a problem with WPF triggers. In my application i used a multitrigger but would like to achieve that changes made when a tri开发者_运维百科gger's conditions become true to persist and NOT to be invalidated when the trigger's conditions become false AGAIN. Is it possible to realize what I want ?

Thanks in advance.


Triggers don't have any memory: As soon as the trigger becomes inapplicable the trigger's setters are unapplied. You want a condition that "locks on" once it has been set. This can be done with a very simple and generic piece of code.

First you need an attached property that you can "lock on". Here's a simple class with a "IsLocked" attached property that becomes true whenever the "DoLock" property is set and stays that way from then on:

public class LockingProperty : DependencyObject
{
  // IsLocked
  public static bool GetIsLocked(DependencyObject obj) { return (bool)obj.GetValue(IsLockedProperty); }
  public static void SetIsLocked(DependencyObject obj, bool value) { obj.SetValue(IsLockedProperty, value); }
  public static readonly DependencyProperty IsLockedProperty = DependencyProperty.RegisterAttached("IsLocked", typeof(bool), typeof(LockingProperty));

  // DoLock
  public static bool GetDoLock(DependencyObject obj) { return (bool)obj.GetValue(DoLockProperty); }
  public static void SetDoLock(DependencyObject obj, bool value) { obj.SetValue(DoLockProperty, value); }
  public static readonly DependencyProperty DoLockProperty = DependencyProperty.RegisterAttached("DoLock", typeof(bool), typeof(LockingProperty), new PropertyMetadata
  {
    PropertyChangedCallback = (obj, e) => { SetIsLocked(obj, true); }
  });
}

Now you can emulate a locking trigger using two separate triggers:

<Triggers>
  <Trigger ... your trigger conditions here ...>
    <Setter Property="my:LockingProperty.DoLock" Value="true" />
  </Trigger>
  <Trigger Property="my:LockingProperty.IsLocked" Value="true" />
    ... your setters here ...
  </Trigger>
</Triggers>

Note that the first trigger in this example can be a Trigger, DataTrigger, MultiTrigger or MultiDataTrigger - whatever you need to express your triggering condition.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜