0

In a WPF window, I'm trying to put the cursor by default on one of the textboxes. After reading some questions and answers, I tried the following:

xaml:

<StackPanel Grid.Row="1"
    <StackPanel.Style>
        <Style>
            <Style.Triggers>
                <DataTrigger Binding="{Binding UserShouldEditValueNow}" Value="true">
                    <Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=FID}"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </StackPanel.Style>
    <TextBox Name ="FID" Text="{Binding FixID, UpdateSourceTrigger=PropertyChanged}" 
    FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}"/>
</StackPanel>

cs: (Viewmodel)

this.UserShouldEditValueNow = true;

I expected to see a blinking cursor on the textbox FID when opening the window. However, there's no cursor at all on this textbox. Debugging showed me that I'm going through the cs code, setting the value to true. any ideas why?

Ron.A
  • 59
  • 1
  • 1
  • 8
  • Try [this](https://stackoverflow.com/a/1356781/6869276) approach for an answer. Add the `FocusExtension` class, remove the StackPanel and go with this: `` Works for me. – pixela Dec 07 '17 at 12:52
  • Possible duplicate of [Set focus on textbox in WPF from view model (C#)](https://stackoverflow.com/questions/1356045/set-focus-on-textbox-in-wpf-from-view-model-c) – techvice Dec 07 '17 at 23:42

1 Answers1

2

Solution involves: 1. Adding a FocusExtension class. 2. Focus and Keyboard.Focus are inside Dispatcher.BeginInvoke

cs.

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

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

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

        private static void OnIsFocusedPropertyChanged(
            DependencyObject d,
            DependencyPropertyChangedEventArgs e)
        {
            var uie = (UIElement)d;
            if ((bool)e.NewValue)
            {
                uie.Dispatcher.BeginInvoke(
                    new Action(
                        delegate{
                            uie.Focus(); 
                            Keyboard.Focus(uie);
                        }
                    )
                );
            }
        }
    }

.xaml

        <TextBox Text="{Binding FixID, UpdateSourceTrigger=PropertyChanged}"  viewModels:FocusExtension.IsFocused="{Binding UserShouldEditValueNow}" />
Ron.A
  • 59
  • 1
  • 1
  • 8