David
David

Reputation: 1062

Silverlight RichTextBox Disable Mouse Selection

I am writing a custom control based on RichTextBox that needs the ability to process MouseLeftButtonDown events but must not allow user-initiated selection (I'm doing everything programmatically).

I tried setting a flag in MouseLeftButtonDown to track dragging and then continuously setting the RichTextBox.Selection to nothing in the MouseMove event but the move event isn't fired until after I release the mouse button.

Any ideas on how to solve this? Thanks.

Upvotes: 1

Views: 1247

Answers (2)

David
David

Reputation: 1062

Here's the solution I came up with:

public class CustomRichTextBox : RichTextBox
{
    private bool _selecting;

    public CustomRichTextBox()
    {
        this.MouseLeftButtonDown += (s, e) =>
        {
            _selecting = true;
        };
        this.MouseLeftButtonUp += (s, e) =>
        {
            this.SelectNone();
            _selecting = false;
        };
        this.KeyDown += (s, e) =>
        {
            if (e.Key == Key.Shift)
                _selecting = true;
        };
        this.KeyUp += (s, e) =>
        {
            if (e.Key == Key.Shift)
               _selecting = false;
        };
        this.SelectionChanged += (s, e) =>
        {
            if (_selecting)
                this.SelectNone();
        };
    }

    protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
    {
        base.OnMouseLeftButtonDown(e);
        e.Handled = false;
    }

    protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
    {
        base.OnMouseLeftButtonUp(e);
        e.Handled = false;
    }

    public void SelectNone()
    {
        this.Selection.Select(this.ContentStart, this.ContentStart);
    }
}

Upvotes: 2

AnthonyWJones
AnthonyWJones

Reputation: 189525

Have you tried e.Handled = true in your event handler to see if that gets you the desired behaviour.

Upvotes: 0

Related Questions