how to set the focus state of a textblock in binding in uwp

27 Views Asked by At

i am using a textblock whose properties are binded to a binding class, i want the focus textblock to be active on certain times , is there any way to bind the focus state of the textblock?

<TextBox x:Name="block1" Text="{Binding Text_ , Mode=TwoWay}"  Style="{ThemeResource TextFieldStyle}"  AllowFocusOnInteraction="True" FontSize="14" MinWidth="274" Height="30" RelativePanel.Below="seperator1" Margin="12 12 12 0" />
1

There are 1 best solutions below

0
Junjie Zhu - MSFT On

It is recommended that you create a dependency property for Textbox to change its focus state.

<Grid>
    <StackPanel>
        <TextBox x:Name="testTextBox" TextWrapping="Wrap" Text="Test Test" Height="113" Width="265"/>
        <Button Content="Button"   Click="Button_Click"/>
        <Button Content="Button" Click="Button_Click_1"/>
    </StackPanel>

</Grid>

public sealed partial class MainPage : Page
{
    public bool IsFocused = true;
    public MainPage()
    {
        this.InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        IsFocused=true;

        testTextBox.SetValue(FocusExtension.IsFocusedProperty, true);
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        IsFocused = false;

        testTextBox.SetValue(FocusExtension.IsFocusedProperty, false);
    }
}

public static class FocusExtension
{
    public static readonly DependencyProperty IsFocusedProperty = DependencyProperty.RegisterAttached(
        "IsFocused", typeof(bool), typeof(FocusExtension), new PropertyMetadata(false, OnIsFocusedPropertyChanged));

    public static bool GetIsFocused(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsFocusedProperty);
    }

    public static void SetIsFocused(DependencyObject obj, bool value)
    {
        obj.SetValue(IsFocusedProperty, value);
    }

    private static void OnIsFocusedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var control = (Control)d;

        if ((bool)e.NewValue)
        {
            control.Focus(FocusState.Programmatic);
        }
    }
}