Chris
Chris

Reputation: 1251

Setting "AcceptButton" from WPF WindowsFormHost

I have a winforms usercontrol with multiple buttons in a WPF Control.

My usercontrol was previously hosted in a windows form and I was able to so

this.ParentForm.AcceptButton = this.btnSearch;

I'm trying to establish how to do similar on the usercontrol now that it is in the WindowsFormHost. The ParentForm property is null.

There are two things I would ideally like to achieve.

  1. AcceptButton behaviour (Enter key triggers button press)
  2. AcceptButton formatting - i.e. the winforms button has the alternate formatting for accept buttons applied.

Many thanks, Chris

Upvotes: 13

Views: 8362

Answers (6)

Jacob
Jacob

Reputation: 667

For using Esc and Enter I used this:

<UserControl.InputBindings>
    <KeyBinding Key="Esc" Command="{Binding CancelCommand}"/>
    <KeyBinding Key="Enter" Command="{Binding SaveCommand}"/>
</UserControl.InputBindings>

Upvotes: 0

farzad.moomeni
farzad.moomeni

Reputation: 31

Set your default button's IsDefault property to true.

Upvotes: 3

raddevus
raddevus

Reputation: 9087

It is unfortunate there is no AcceptButton in WPF -- and annoying.

I successfully implemented the functionality by handling the Form's KeyUp event. Here's the code:

private void Window_KeyUp(object sender, KeyEventArgs e)
{
   if(e.Key == Key.Enter)
   {
      TargetButton_Click(sender, null);
   }
 }  

Seems to work fine. In my case I have textboxes on the WPF form and the user enters values and hits and it seems to work fine. There may be issues with some control which overrides (grabs the KeyUp event) before the form or something so your mileage may vary. :)

Upvotes: -1

TrialAndError
TrialAndError

Reputation: 1854

Set Button.IsCancel (Esc) or IsDefault (Enter) on the Buttons in the page.

Example:

<Button Content="Yes" Click="Yes_Button_Click" IsDefault="True"/>
<Button Content="No" Click="No_Button_Click" IsCancel="True"/>

Upvotes: 33

user7116
user7116

Reputation: 64148

WPF Windows do not have the Windows Forms concept of an AcceptButton. You likely will not be able to get the Enter key to automatically engage your btnSearch.Click handler. Also, you will not be able to get the alternate style for the accept button as well.

You could potentially expose a method on your Windows Forms control which acts like you clicked the search button, and call that method from the WPF side when the Enter key is pressed. Otherwise, you'll find that interaction between Forms controls and WPF controls are lacking (WindowsFormsHost was never intended to provide full fidelity access).

Upvotes: 0

Aykut &#199;evik
Aykut &#199;evik

Reputation: 2088

I'm not sure, but can you set the focus to that button? So it would have the same behavior as in winforms.

Upvotes: -1

Related Questions