要调用您的触发器操作,您需要一个触发器!
namespace TriggerTest
{
using System.Windows;
/// <summary>
/// A trigger that may be invoked from code.
/// </summary>
public class ManualTrigger : System.Windows.Interactivity.TriggerBase<DependencyObject>
{
/// <summary>
/// Invokes the trigger's actions.
/// </summary>
/// <param name="parameter">The parameter value.</param>
public void Invoke(object parameter)
{
this.InvokeActions(parameter);
}
}
}
上面是一个触发器实现,可以在没有任何 UI 依赖项的情况下调用。例如:
var measure = new MeasureAction();
measure.TargetObject = _mapControl;
measure.MeasureMode = MeasureAction.Mode.Polyline;
measure.MapUnits = DistanceUnit.Miles;
ManualTrigger trigger = new ManualTrigger();
trigger.Actions.Add(measure);
trigger.Invoke(null);
为了使调用更容易,您可以将扩展方法添加到TriggerAction
.
namespace TriggerTest
{
using System.Windows.Interactivity;
/// <summary>
/// Allows a trigger action to be invoked from code.
/// </summary>
public static class TriggerActionExtensions
{
/// <summary>
/// Invokes a <see cref="TriggerAction"/> with the specified parameter.
/// </summary>
/// <param name="action">The <see cref="TriggerAction"/>.</param>
/// <param name="parameter">The parameter value.</param>
public static void Invoke(this TriggerAction action, object parameter)
{
ManualTrigger trigger = new ManualTrigger();
trigger.Actions.Add(action);
try
{
trigger.Invoke(parameter);
}
finally
{
trigger.Actions.Remove(action);
}
}
/// <summary>
/// Invokes a <see cref="TriggerAction"/>.
/// </summary>
/// <param name="action">The <see cref="TriggerAction"/>.</param>
public static void Invoke(this TriggerAction action)
{
action.Invoke(null);
}
}
}
现在你可以写出你真正想要的:
var measure = new MeasureAction();
measure.TargetObject = _mapControl;
measure.MeasureMode = MeasureAction.Mode.Polyline;
measure.MapUnits = DistanceUnit.Miles;
measure.Invoke();