tags:

views:

202

answers:

1

In WPF, you can assign a label a mnemonic, and tell it which control to activate with the "Target" property.

This doesn't work if the target is a WindowsFormsHost. Is there a known solution to this?

Here's an example. I am trying to make ALT-S activate the masked text box.

<Label 
   Width="Auto" 
   Target="{Binding ElementName=tbStartTime}" 
   TabIndex="12">
   _Start Time:
</Label>
<WindowsFormsHost 
    Name="tbStartTime" 
    TabIndex="13">
 <wf:MaskedTextBox Name="wfStartTime"  Mask="90:00" />
/WindowsFormsHost>
+1  A: 

I don't think it's possible, at least not without some extra boilerplate code... WPF and Windows Forms have a completely different model, and the Target property isn't designed to refer to WinForms controls.

Instead, I think you should use a WPF implementation of MaskedTextBox, like this one (you can find many other examples with Google). Using WinForms controls in a WPF app is rarely a good idea if you can avoid it...

EDIT: I just checked the doc : it is definitely not possible to do what you want, because the type of the Label.Target property is UIElement, and WinForms controls are clearly not UIElements...


UPDATE: OK, I misread your code... you're referencing the WindowsFormsHost, which is a UIElement. Whoever voted me up was wrong too ;-)

I think the problem is that the WindowsFormsHost takes the focus when you press Alt-S, not the MaskedTextBox. Here's a quick workaround :

XAML :

<WindowsFormsHost 
    Name="tbStartTime" 
    TabIndex="13"
    GotFocus="tbStartTime_GotFocus">
 <wf:MaskedTextBox Name="wfStartTime"  Mask="90:00" />
</WindowsFormsHost>

Code-behind :

    private void tbStartTime_GotFocus(object sender, RoutedEventArgs e)
    {
        tbStartTime.Child.Focus();
    }

Anyway, my previous advice is still relevant : you'd better use a WPF MaskedTextBox...

Thomas Levesque
That has to be a mistake by the WPF team. It's such an obvious thing - if you focus a WindowsFormsHost, what else should happen other than the child control becomes focused? Still, I'm happy there's a one-line workaround.
Andrew Shepherd
IMO, a really clean workaround wouldn't involve writing code behind... this one could easily be wrapped in a reusable attached property
Thomas Levesque