AndyDB
AndyDB

Reputation: 431

Returning the name of a control

I have a simple XAML form within my WPF/C# app, containing several textboxes. I need to know the name of the control when either TAB or ENTER keys are pressed - but I don't know how to do this.

I have a function that listens for the Enter / Tab keys, but after that - I'm stumped:

public viewSearch()
{
    InitializeComponent();
    PreviewKeyDown += new KeyEventHandler(HandleEsc);
}

private void HandleEsc(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Escape) Close();
    if (e.Key == Key.Enter) SearchAndDisplay();
    if (e.Key == Key.Tab) SearchAndDisplay();
}   

private void SearchAndDisplay()
{
    MessageBox.Show("THE NAME OF THE CONTROL");
} 

Thank you.

Upvotes: 0

Views: 59

Answers (1)

Recipe
Recipe

Reputation: 1406

If you're looking for the control that triggers the event, you could try something as follows: (pseudocode, since I currently have no access to Visual Studio and I can't directly check if this is all valid for WPF):

private void HandleEsc(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Escape) Close();
    if (e.Key == Key.Enter ||
        e.Key == Key.Tab) SearchAndDisplay(e.OriginalSource)
}   

private void SearchAndDisplay(object sender)
{
    if(sender is Control)
    {
        MessageBox.Show(((Control)sender).Name);
    }
} 

Upvotes: 3

Related Questions