stacker flow stacker flow - 1 month ago 12
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">
<i:Interaction.Triggers>
<e:PropertyChangedTrigger>
<i:Interaction.Behaviors>
<e:ConditionBehavior>
<e:ConditionalExpression>
<e:ComparisonCondition LeftOperand="{Binding SearchBox.IsKeyboardFocused}" Operator="Equal" RightOperand="rue" />
</e:ConditionalExpression>
</e:ConditionBehavior>
</i:Interaction.Behaviors>
<e:ChangePropertyAction TargetName="SearchLabel" PropertyName="Visibility" Value="Hidden" />
</e:PropertyChangedTrigger>
</i:Interaction.Triggers>
</TextBox>
<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

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

<UserControl.Resources>
    <YourNamespace:BoolToVisConverter x:Key="BoolToVis" />
</UserControl.Resources>
...
<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