gpt4 book ai didi

c# - 如何在代码中创建控件时将点击事件绑定(bind)到 ViewModel

转载 作者:行者123 更新时间:2023-11-30 16:16:24 25 4
gpt4 key购买 nike

通常,我在 XAML 中创建 View ,并使用 Caliburn.Micro 将事件绑定(bind)到 View 模型。

<Button cal:Message.Attach="[MouseLeftButtonUp]=[ModifyList($source)]" />

但是,我现在需要根据配置数据在代码中创建按钮。

代码不在代码隐藏中,它在工厂类中。

Button button = new Button() { Content = "Click Me" };

那么问题是如何连接事件?

最佳答案

我以前从未这样做过,所以这可能不是最好的方式,但它确实有效。

我在下面编写了一个扩展方法,应该可以非常简单地将 ActionMessage 附加到任何控件的任何事件。

public static class UIElementExtension {
public static void AttachActionMessage(this DependancyObject control, string eventName, string methodName, object parameter) {
var action = new ActionMessage();
action.MethodName = methodName;
action.Parameters.Add(new Parameter { Value = parameter });

var trigger = new System.Windows.Interactivity.EventTrigger();
trigger.EventName = eventName;
trigger.SourceObject = control;
trigger.Actions.Add(action);

Interaction.GetTriggers(control).Add(trigger);
}
}

要使用它,只需创建您的控件并调用 AttachActionMessage():

var button = new Button { Content = "Click Me" };
button.AttachActionMessage("Click", "ModifyList", DataContext);

关于c# - 如何在代码中创建控件时将点击事件绑定(bind)到 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18429355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com