Changing focus in xaml
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();
}
});
}
精彩评论