I have an MVVM Light-based WPF application where I'm having problems setting focus on a particular button based on viewmodel conditions.
Here's the relevant XAML:
<ContentControl Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="2"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
IsTabStop="False"
Content="{Binding PageControl, Mode=OneWay}"
Name="ctlCurrent"/>
<Button Style="{DynamicResource MaoStandardButton}"
IsDefault="True"
support:FocusExtension.IsFocused="{Binding DefaultButtonIsSelected}"
TabIndex="1">
<Button.IsEnabled>
<MultiBinding Converter="{StaticResource AllTrueConverter}">
<Binding Path="IsDirty"/>
<Binding Path="IsValid"/>
</MultiBinding>
</Button.IsEnabled>
Save & New
</Button>
There are two viewmodels in operation here. The first is the parent, to which the controls shown are bound. The second is bound to the UserControl
, which is exposed by the parent's PageControl property (this second viewmodel is bound to the UserControl
's DataContext
).
The two viewmodels communicate behind the scenes, with the second/child viewmodel controlling the parent viewmodel properties of IsDirty
and IsValid
(this is done based on evaluating changes to the child viewmodel's properties, and their validity). Conceptually, what I want to happen is this: whenever the last control in the UserControl loses focus, and the child viewmodel IsDirty
and IsValid
, I want focus to shift to the Save & New button.
Part of implementing this involved adding an attached property to the Save & New button, based on this SO article.
That's the basis of the support:FocusExtension
... XAML. The parent viewmodel property DefaultButtonIsSelected
is set when the last control in the UserControl loses focus, and everything IsValid
and IsDirty
.
Unfortunately, while I can see the focus-controlling code in the attached property being called, as soon as the Save & New button gets focus, it immediately loses it (and the focus-lost code from that article gets called).
I'm pretty sure this is due to the timing of when WPF is evaluating the value of the button's IsEnabled
property. I say this because commenting out the multiconverter -- so the button is always enabled -- lets the focus setting control work as expected -- focus is set on the button, and not lost.
Is there a way to force WPF to re-evaluate tab stops after the Save & New button's IsEnabled
property changes? I think that might solve the problem. Other ideas are welcome, too, of course.