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.FocusedElementcontrols only the local focus within aFocusScope. Since theButtonis 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 aPropertyChangedCallback, something like this: