How to check if any of three controls has focus at same time in wpf?

Relativity picture Relativity · Nov 14, 2011 · Viewed 7.5k times · Source

I have a three textboxes...and I wanted to check if any of these three has focus in it.

I tried something like this -> added three properties in viewmodel...whose value will be toggled by lost/got focus events. (I did this through attached properties). But in this case...if I move foucs from one textbox to next...first textbox's focus become false...and next one is yet to set...So in this condition none of these textboxes has focus...but second one will gain focus soon.

As a work around, I am trying to use Group box...to check if this control has focus instead of checking all three. Please tell me if this work

Answer

Rachel picture Rachel · Nov 14, 2011

Why do you need to know if they have Focus or not?

Focus is a View-Specific function, so I would expect your ViewModels not to care about it.

Usually if I am doing something based on control Focus, it is for a View-Specific action such as a DataTrigger, and in that case I use code-behind or a Trigger

Code behind example

if (tb1.IsFocused||  tb2.IsFocused || tb3.IsFocused)
{
    DoSomething();
}

Trigger example

<Style.Triggers>
    <DataTrigger Binding="{Binding IsFocused, ElementName=tb1}" Value="True">
        <Setter Property="BorderBrush" Value="Red" />
    </DataTrigger>

    <DataTrigger Binding="{Binding IsFocused, ElementName=tb2}" Value="True">
        <Setter Property="BorderBrush" Value="Red" />
    </DataTrigger>
    <DataTrigger Binding="{Binding IsFocused, ElementName=tb3}" Value="True">
        <Setter Property="BorderBrush" Value="Red" />
    </DataTrigger>
</Style.Triggers>