Tony
Tony

Reputation: 1714

WPF TextBox Overwrite

In WPF, is there an easy to allow overwriting of text in an textbox?

Thanks
Tony

EDIT: I guess i wasn't to clear. Sorry.

I have a TextBox that the user is allowed to type 6 characters. If the user types 6 characters and then for whatever reason put the cursor at the start or somewhere in the middle of the 6 characters and starts to type, I want what they are typing to overwrite characters. Basically act like overwrite mode in Word.

Thanks again.

Upvotes: 2

Views: 6135

Answers (4)

k1ll3r8e
k1ll3r8e

Reputation: 747

Heyho, i know this question is super old, but i was looking for an solution to archive the "override" behaviour via MVVM pattern. So i wrote the following DependencyProperty, hope it will help someone.

public class ElementBehavior
{
   #region ForceOverride

    ///<summary>
    /// DependencyProperty
    ///</summary>
    public static readonly DependencyProperty ForceOverrideProperty = DependencyProperty.RegisterAttached("ForceOverride", typeof(bool), typeof(ElementBehavior), new PropertyMetadata(false, (s, e) =>
    {
        if (s is TextBoxBase t)
        {
            if ((bool)e.NewValue)
            {
                t.PreviewKeyDown += OnForceOverride;
            }
            else
            {
                t.PreviewKeyDown -= OnForceOverride;
            }
        }
    }));

    ///<summary>
    /// Get
    ///</summary>
    ///<param name="target"><see cref="DependencyObject"/></param>
    ///<returns><see cref="bool"/></returns>
    public static bool GetForceOverride(DependencyObject target)
    {
        return (bool)target.GetValue(ForceOverrideProperty);
    }

    ///<summary>
    /// Set
    ///</summary>
    ///<param name="target"><see cref="DependencyObject"/></param>
    ///<param name="value"><see cref="bool"/></param>
    public static void SetForceOverride(DependencyObject target, bool value)
    {
        target.SetValue(ForceOverrideProperty, value);
    }

    private static void OnForceOverride(object sender, KeyEventArgs e)
    {
        Key[] BAD_KEYS = new Key[] { Key.Back, Key.Delete };
        Key[] WRK_KEYS = new Key[] { Key.Left, Key.Up, Key.Right, Key.Down, Key.Enter };
        if (BAD_KEYS.Contains(e.Key))
        {
            e.Handled = true;
        }
        else if (!WRK_KEYS.Contains(e.Key))
        {
            if (sender is RichTextBox r)
            {
                if (!string.IsNullOrEmpty(new TextRange(r.Document.ContentStart, r.Document.ContentEnd).Text))
                {
                    r.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Input, (Action)delegate
                    {
                        TextPointer tp = r.CaretPosition.GetNextInsertionPosition(LogicalDirection.Forward);
                        if (tp != null && tp != r.Document.ContentEnd)
                        {
                            r.Selection.Select(r.CaretPosition, tp);
                        }
                    });
                }
            }
            else if (sender is TextBox t)
            {
                if (!string.IsNullOrEmpty(t.Text))
                {
                    t.Select(t.CaretIndex, 1);
                }
            }
        }
    }
    #endregion
}

Usage:

 <Style TargetType="{x:Type TextBox}">
       <Setter Property="ElementBehavior.ForceOverride" Value="True"/>
 </Style>

Upvotes: 5

Kent Boogaart
Kent Boogaart

Reputation: 178630

Assuming you mean select some text and then allow the user to type over that text:

//select the third character
textBox.Select(2, 1);

Upvotes: 1

raf
raf

Reputation: 150

I would avoid reflection. The cleanest solution is the following:

EditingCommands.ToggleInsert.Execute(null, myTextBox);

Upvotes: 6

Robert Macnee
Robert Macnee

Reputation: 11820

Looking at it in Reflector, this seems to be controlled from the boolean TextBoxBase.TextEditor._OvertypeMode internal property. You can get at it through reflection:

// fetch TextEditor from myTextBox
PropertyInfo textEditorProperty = typeof(TextBox).GetProperty("TextEditor", BindingFlags.NonPublic | BindingFlags.Instance);
object textEditor = textEditorProperty.GetValue(myTextBox, null);

// set _OvertypeMode on the TextEditor
PropertyInfo overtypeModeProperty = textEditor.GetType().GetProperty("_OvertypeMode", BindingFlags.NonPublic | BindingFlags.Instance);
overtypeModeProperty.SetValue(textEditor, true, null);

Upvotes: 4

Related Questions