我需要使用一些带有交互触发器的附加条件,例如:
作为对事件的反应,我想执行命令,但前提是条件匹配。另外我希望命令会延迟执行。我可以用那个伪 xaml 来表达这一点。
<ci:RoutedEventTrigger Event="{x:Static Selector.SelectionChangedEvent}">
<li:TriggerCondition ActualValue="{Binding Value}" ExpectedValue="{StaticResource foo}">
<li:DelayAction DelayTime="{StaticResource delayTime}">
<InvokeCommandAction CommandName="{StaticResourc commandName}"/>
</li:DelayAction>
</li:TriggerCondition>
</ci:RoutedEventTrigger>
我尝试编写 TriggerCondition 和 DelayAction 类,但几乎所有交互代码都是内部的。
所以问题是我怎样才能达到期望的行为?使用条件和延迟编写 RoutedEventTrigger 看起来并不那么通用,而且我还有 InputBindingTrigger 等等。
提前致谢
更新: 我已经使用反射制作了我想要的东西,但我仍在寻找你的建议如何以正确的方式做到这一点:)
[ContentProperty("Actions")]
public abstract class TriggerDecorator : TriggerAction<DependencyObject>
{
private static readonly DependencyPropertyKey ActionsPropertyKey =
DependencyProperty.RegisterReadOnly("Actions", typeof (TriggerActionCollection),typeof (TriggerDecorator), new FrameworkPropertyMetadata());
public static readonly DependencyProperty ActionsProperty = ActionsPropertyKey.DependencyProperty;
public TriggerActionCollection Actions
{
get { return (TriggerActionCollection) GetValue(ActionsProperty); }
}
private readonly MethodInfo myTriggerAction_CallInvokeMethod;
public TriggerDecorator()
{
var triggerActionType = typeof (TriggerAction);
myTriggerAction_CallInvokeMethod = triggerActionType.GetMethod("CallInvoke", BindingFlags.Instance | BindingFlags.NonPublic);
if(myTriggerAction_CallInvokeMethod == null)
throw new InvalidOperationException();
var actionCollection = (TriggerActionCollection)Activator.CreateInstance(typeof(TriggerActionCollection), true);
SetValue(ActionsPropertyKey, actionCollection);
}
protected override void OnAttached()
{
base.OnAttached();
if(AssociatedObject == null)
return;
Actions.Attach(AssociatedObject);
}
protected override void OnDetaching()
{
base.OnDetaching();
Actions.Detach();
}
protected void ExecuteActions(object parameter)
{
var param = new[] {parameter};
foreach (var triggerAction in Actions)
myTriggerAction_CallInvokeMethod.Invoke(triggerAction, param);
}
}