WPF - Events from Inside User Control

We are having a problem creating events for a custom control in WPF. We have our code:


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));

code>

The control is an on-screen keyboard, and we basically need to pass KeyPressedEventArgs participants to subscribers of an event that describes which key was pressed (we cannot find much that helps us with this in WPF, only winforms).

Any help greatly appreciated!

+3
source share
1 answer

Step 1: add the event handler to OK and the Cancel button

private void btnOK_Click(object sender, RoutedEventArgs e)
{     
}

private void btnCancel_Click(object sender, RoutedEventArgs e)
{     
}

Add a public property in the UserControl1.xaml.cs file to share the text field value with the host

public string UserName
{
    get { return txtName.Text; }
    set { txtName.Text = value; }
}

"" "", Windows Form.

public event EventHandler OkClick;
public event EventHandler CancelClick;

, .

private void btnOK_Click(object sender, RoutedEventArgs e)
{
    if (OkClick != null)
        OkClick(this, e);
}

private void btnCancel_Click(object sender, RoutedEventArgs e)
{
    if (CancelClick != null)
        CancelClick(this, e);
}

2: WPF Windows

OKClick CancelClick

_WPFUserControl.OkClick += new EventHandler(OnOkHandler);
_WPFUserControl.CancelClick += new EventHandler(OnCancelHandler);

. UserName OK, , .

protected void OnOkHandler(object sender, EventArgs e)
{
    MessageBox.Show("Hello: " +_WPFUserControl.UserName + " you clicked Ok Button");
}

protected void OnCancelHandler(object sender, EventArgs e)
{
    MessageBox.Show("you clicked Cancel Button");
}

: http://a2zdotnet.com/View.aspx?Id=79

+7

All Articles