开发者

Changing focus in xaml

开发者 https://www.devze.com 2022-12-17 10:11 出处:网络
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 i

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.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号