Change focus in xaml

I have a problem with focus on some button on xaml. The code I'm trying to do is as follows (if some conditions are met, then the focus should be set to the button. It is strange that for testing purposes I also look at the background of the button, and this property is set every time the conditions are met. How to set the button by default or set focus on this 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>

In addition, I would like to write that SomeProperty1 and SomeProperty2 are installed only if I click on a specific button. As I can see, these buttons have focus.

+3
source share
1 answer

, FocusManager.FocusedElement FocusScope. Button FocusScope, . Focus(), , .

, "MyFocusManager.ForceFocus", false true FocusManager.FocusedElement. PropertyChangedCallback, :

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();
      }
    });
}
+3

Source: https://habr.com/ru/post/1729351/


All Articles