小编JBe*_*gle的帖子

WPF - 来自用户控件内部的事件

尝试在WPF中为自定义控件创建事件时遇到问题.我们的代码如下:


public static readonly RoutedEvent KeyPressedEvent =
            EventManager.RegisterRoutedEvent(
                "keyPressed", RoutingStrategy.Bubble,
                    typeof(KeyEventHandler), typeof(Keyboard));

    public event KeyEventHandler keyPressed
    {
        add { AddHandler(KeyPressedEvent, value); }
        remove { RemoveHandler(KeyPressedEvent, value); }
    }

void btnAlphaClick(object sender, RoutedEventArgs e)
    {
        var btn = (Button)sender;
        Key key = (Key)Enum.Parse(typeof(Key), btn.Content.ToString().ToUpper());
        PresentationSource source = null;
        foreach (PresentationSource s in PresentationSource.CurrentSources)
        {
            source = s;
        }
        RaiseEvent(new KeyEventArgs(InputManager.Current.PrimaryKeyboardDevice, source,0,key));
Run Code Online (Sandbox Code Playgroud)

该控件是一个屏幕键盘,我们基本上需要传递给KeyPressedEventArgs给事件的订阅者详细说明按下了什么键(我们找不到太多帮助我们在WPF中使用它,只有winforms).

任何帮助,非常感谢!

c# wpf events wpf-controls

3
推荐指数
1
解决办法
9019
查看次数

标签 统计

c# ×1

events ×1

wpf ×1

wpf-controls ×1