tags:

views:

278

answers:

1

Greetings, I have a problem changing the focus to some button on xaml. The code I am attemps to do it looks as follows (if some conditions are fulfilled then the focus should be set to the button. The strange is that for test purposes I'm also chaning the background of the button and this property is set each time the conditions are fulfilled. How can I set the default button or set the focus on that button?

<Button.Style>
<Style TargetType="{x:Type Button}">
<Style.Triggers>
  <MultiDataTrigger>
    <MultiDataTrigger.Conditions>
      <Condition Binding="{Binding Path=SomeProperty1.Count, Converter={StaticResource IntegerToBooleanConverter}}" Value="True"/>
      <Condition Binding="{Binding Path=SomeProperty2, Converter={StaticResource NullToBoolConverter}}" Value="False"/>
      <Condition Binding="{Binding Path=SomeProperty3.Count, Converter={StaticResource IntegerToBooleanConverter}}" Value="True"/> 
    </MultiDataTrigger.Conditions>
    <Setter Property="FocusManager.FocusedElement" Value="{Binding RelativeSource={RelativeSource Self}}"/>
    <Setter Property="IsDefault" Value="True"/> 
    <Setter Property="Background" Value="Green"/>
  </MultiDataTrigger>
</Style.Triggers>

additionally i would like to write that SomeProperty1 and SomeProperty2 are set only if I click on the specific button. As I can see these buttons have then the focus.

+1  A: 

The problem is that FocusManager.FocusedElement controls only the local focus within a FocusScope. Since the Button is not its own FocusScope it has no effect. You need to call the Focus() method, which requires you to write some code.

You could do the obvious and write an event handler, or you could do the non-obvious and create an attached property "MyFocusManager.ForceFocus" that, when transitioning from false to true, sets FocusManager.FocusedElement. This is done with a PropertyChangedCallback, something like this:

public class MyFocusManager
{
  public static bool GetForceFocus .... // use "propa" snippet to fill this in
  public static void SetForceFocus ....
  public static DependencyProperty ForceFocusProperty = DependencyProperty.RegisterAttached("ForceFocus", typeof(bool), typeof(MyFocusManager),  new UIPropertyMetadata
    {
      PropertyChangedCallback = (obj, e) =>
      {
        if((bool)e.NewValue && !(bool)e.OldValue & obj is IInputElement)
          ((IInputElement)obj).Focus();
      }
    });
}
Ray Burns
ok, I will try that and let you know if it works
niao
well, It doesn't work. PropertyChangedCallback is indeed executed but the focus is is still on the other button.
niao
it works after I've set the Focusable property for the two others buttons to false
niao
Sorry, my bad. You need to call the `Focus()` method to change the focus. The `Focus()` method will find the correct scope and set the scope's `FocusedElement` attached property. See my corrected answer.
Ray Burns