【问题标题】:How to create an event trigger for control programmatically如何以编程方式为控件创建事件触发器
【发布时间】:2014-07-17 16:31:46
【问题描述】:

我想以编程方式为我的 ContentControl 创建一个事件触发器。我想获得与使用此 xaml 代码相同的结果。包括——Command、CommandParameter、EventName

它在我的 xaml 代码中的外观:

<ContentControl>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="PreviewMouseLeftButtonDown">
            <i:InvokeCommandAction Command="{Binding ButtonClickCommand}" CommandParameter="btnAdd"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</ContentControl>

【问题讨论】:

  • 阅读“我想做的是以编程方式创建一个事件触发器来命令 ContentControl。”,忘记你知道你的问题,并想象你应该明白你想说什么。我一个人不懂你
  • 现在@AndreasMüller 是否更清楚了?
  • 肯定更好,是的

标签: c# wpf


【解决方案1】:

下面是等效的代码:

void SetTrigger(ContentControl contentControl)
{
    // create the command action and bind the command to it
    var invokeCommandAction = new InvokeCommandAction { CommandParameter = "btnAdd" };
    var binding = new Binding { Path = new PropertyPath("ButtonClickCommand") };
    BindingOperations.SetBinding(invokeCommandAction, InvokeCommandAction.CommandProperty, binding);

    // create the event trigger and add the command action to it
    var eventTrigger = new System.Windows.Interactivity.EventTrigger { EventName = "PreviewMouseLeftButtonDown" };
    eventTrigger.Actions.Add(invokeCommandAction);

    // attach the trigger to the control
    var triggers = Interaction.GetTriggers(contentControl);
    triggers.Add(eventTrigger);
}

【讨论】:

  • 非常感谢!你是救生员。 :)
猜你喜欢
  • 1970-01-01
  • 2012-08-24
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 2017-05-22
  • 2017-03-02
  • 1970-01-01
相关资源
最近更新 更多