3

I have some control in a stackpanel.
When I right click on the panel it gives me a context menu and I can edit the text of these control.
Here I used TextBlock to display the data and TextBox to edit the data (When TextBox is visible TextBlock become collapsed and vice versa)
I want to select all the text of the TextBox and focus it when the TextBox is visible.

I tried using Interaction. But didn't work out :(
Is there any way to do this?
For example : When the TextBox is visible I can fire some command in my viewmodel and select all the text from my viewmodel.

<TextBlock Text="{Binding MachineResponseText}" Visibility="{Binding IsEditing, Converter={StaticResource BoolToVisibilityConverter}, ConverterParameter=true}"/>
<TextBox x:Name="MachineResponseTextBox" Text="{Binding MachineResponseText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Visibility="{Binding IsEditing, Converter={StaticResource BoolToVisibilityConverter}}">
    <TextBox.Style>
        <Style TargetType="TextBox">
            <Style.Triggers>
                <Trigger Property="IsVisible" Value="True">
                    <!--Is there any way to select all the text when this textbox is visible?-->
                </Trigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
</TextBox>
Ali Akber
  • 3,670
  • 3
  • 26
  • 40
  • What you want is to "highlight" all of the text in a `TextBox`, so your `VM` should stay out of it. This sounds to me like a code behind solution as the `VM` doesn't really care if the text is selected or not. Unless I misunderstood you? – XAMlMAX May 18 '17 at 12:51
  • Yeah thats true. I don't have to use VM. But how can I highlight the text and focus keyboard on the text field? – Ali Akber May 18 '17 at 12:57
  • The `TextBox` has a `SelectedText` Property which you could set on `gotFocus` `event`. But if this is just switching between edit mode why not manipulate `IsEnabled` property on `TextBox`? – XAMlMAX May 18 '17 at 14:11
  • Possible duplicate of [How to automatically select all text on focus in WPF TextBox?](https://stackoverflow.com/questions/660554/how-to-automatically-select-all-text-on-focus-in-wpf-textbox) – Herohtar Oct 17 '19 at 01:18

4 Answers4

0

This is not complete answer to your question, more of push into proper direction.

Add GotKeyboardFocus handler to your textbox and run textbox.SelectAll(), i.e.

XAML part:

<StackPanel>
    <Button>B1</Button>
    <TextBox Text="Test123" GotKeyboardFocus="TextBox_GotKeyboardFocus"/>
    <TextBlock>123</TextBlock>
    <Button>B2</Button>
</StackPanel>

Code behind part:

private void TextBox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    var textBox = (TextBox) sender;
    if (textBox.SelectionLength == 0)
    {
        textBox.SelectAll();
    }
}

You might need to handle keyboard focus as well by calling TextBox.Focus() upon switching to edit mode, or in more MVVM way as explained here

Community
  • 1
  • 1
Alex Seleznyov
  • 905
  • 6
  • 18
0

If you want to use the MVVM design pattern, I would suggest do it this way.

  1. First you have to create a Extension method as below.

    public static class IsSelectTextExtension
    {
    public static readonly DependencyProperty IsSelectTextProperty = DependencyProperty.RegisterAttached("IsSelectText", typeof(bool), typeof(IsSelectTextExtension), new UIPropertyMetadata(false, OnIsSelectTextPropertyChanged));
    
    public static bool GetIsSelectText(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsSelectTextProperty);
    }
    
    public static void SetIsSelectText(DependencyObject obj, bool value)
    {
        obj.SetValue(IsSelectTextProperty, value);
    }
    
    private static void OnIsSelectTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var uie = (TextBox)d;
        if ((bool)e.NewValue)
        {
            uie.SelectAll();
        }
    }
    }
    
    1. Include the namespace to the view and in your view (.xaml file) bind bool property to the extension that we created above.

<Window x:Class="POS.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfExample"
        xmlns:extension="clr-namespace:WpfExample.Extension"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <TextBox extension:IsSelectTextExtension.IsSelectText="{Binding IsSelectText}"/>
    </Grid>
</Window>
  1. In the view model class, define IsSelectText property and change the value according to your requirement.

    public class MainWindowViewModel: INotifyPropertyChanged
    {
    private bool _isSelectText;
    public bool IsSelectText
    {
        get
        {
            return this._isSelectText;
        }
        set
        {
            _isSelectText = value;
            OnPropertyChanged(nameof(IsSelectText));
        }
    }
    
    public NewSaleViewModel()
    {
    }
    
    #region INotifyPropertyChanged Implimentations
    
    public event PropertyChangedEventHandler PropertyChanged;
    
    protected virtual void OnPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    
    #endregion
    }
    
Prabodha
  • 520
  • 1
  • 6
  • 19
0

What you are asking for is usually the preferred TextBox behavior. You can change this for all text boxes in App.xaml.cs:

protected override void OnStartup(StartupEventArgs e)
{
    // ...
    EventManager.RegisterClassHandler(typeof(TextBox),
        UIElement.GotFocusEvent, new RoutedEventHandler(OnTextBoxGotFocus));
}

private static void OnTextBoxGotFocus(object sender, RoutedEventArgs e)
{
    if (sender is TextBox textBox && !textBox.IsReadOnly)
    {
        textBox.SelectAll();
    }
}
l33t
  • 18,692
  • 16
  • 103
  • 180
-1

There's an event that you can use and it's appliend in all UIElement UIElement.IsVisibleChanged After that you have to make the focus in the textbox and select the text like this

private void TextBox_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    this.myTextBox.Focus();
    this.myTextBox.SelectAll();
}

this is a code behind version you can do the same in a mvvm context by firing the event in your view model.

this stackoverflow post might help you if you want to set a textbox focus in mvvm.

How to set focus to textbox using MVVM?

Hicham Bouchilkhi
  • 682
  • 10
  • 29