stacker flow stacker flow - 1 year ago 104
C# Question

How to write trigger to textbox IskeyboardFocused property

I am trying to change other UI element visibility when textbox is focused. I think that isKeyboardFocused event may solve my problem. So i write my xaml as following.

<TextBox x:Name="SearchBox" Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Stretch">
<e:ComparisonCondition LeftOperand="{Binding SearchBox.IsKeyboardFocused}" Operator="Equal" RightOperand="rue" />
<e:ChangePropertyAction TargetName="SearchLabel" PropertyName="Visibility" Value="Hidden" />
<TextBlock x:Name="SearchLabel" Text="Search" FontStyle="Italic" Foreground="Gray" IsHitTestVisible="False" Visibility="Visible" />

This trigger is not working and i could'nt find the problem. What can i do to fix this problem or any other idea about it?

Answer Source

I would bind the Visibility to the IsKeyboardFocused property as follows:

    <YourNamespace:BoolToVisConverter x:Key="BoolToVis" />
<TextBox x:Name="SearchBox" />
<Label Visibility="{Binding ElementName=SearchBox, Path=IsKeyboardFocused, Converter={StaticResource BoolToVis}, ConverterParameter='invert'}">hello</Label>

using a customized BoolToVisibilityConverter:

public class BoolToVisConverter : IValueConverter
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        if (!(value is bool)) throw new ArgumentException("bool value expected");

        Visibility invisibleMode = (parameter == null || !(parameter is string) ||
                                    !((string) parameter).ToLower().Contains("hidden"))
                                       ? Visibility.Collapsed
                                       : Visibility.Hidden;

        if ((parameter as string)?.ToLower().Contains("invert") ?? false) return (!(bool) value) ? Visibility.Visible : invisibleMode;

        return ((bool) value) ? Visibility.Visible : invisibleMode;

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        throw new NotImplementedException();

The Converter parses given CommandParameter string for: - "invert": true --> invisible, false --> visible - "hidden": invisble case leads to Visibilitys.Hidden, otherwise it's Visibility.Collapsed

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download