Как получить индекс символа в текстовом поле Silverlight в обработчике кликов? - PullRequest
1 голос
/ 20 июля 2010

В частности, я хотел бы, чтобы пользователь щелкнул правой кнопкой мыши в TextBox, выяснил и сохранил позицию индекса в тексте, где произошел щелчок правой кнопкой мыши, а затем вставил немного текста в эту позицию, как толькопользователь делает выбор из контекстного меню, которое появляется из-за щелчка правой кнопкой мыши.

Сложная часть заключается в получении позиции индекса на основе координат щелчка правой кнопкой мыши.

Это вSilverlight 4.

        private int _insertPoint;
    private void userNotification_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
    {
        // Move and open the context menu relative to its container.
        contextMenu.HorizontalOffset = e.GetPosition(container).X;
        contextMenu.VerticalOffset = e.GetPosition(container).Y;
        contextMenu.IsOpen = true;

        // Get the click coordinates relative to the TextBox.
        int clickX = e.GetPosition(textBox).X;
        int clickY = e.GetPosition(textBox).Y;
        _insertPoint = ?; // Here's the problem.
    }

    private void SelectFieldToInsert(object sender, MouseButtonEventArgs e)
    {
        // Close the context menu.
        contextMenu.IsOpen = false;

        var item = sender as ListBoxItem;
        textBox.Text = textBox.Text.Insert(_insertPoint, "<" + item.Content + ">");
    }

Ответы [ 2 ]

1 голос
/ 20 июля 2010

Свойство TextBox.SelectionStart в текстовом поле должно помочь вам. По ссылке:

Если выбора нет, значение SelectionStart возвращает или устанавливает местоположение курсора.

0 голосов
/ 20 июля 2010

Как насчет:

    // Get the click coordinates relative to the TextBox.
    int clickX = (int)e.GetPosition(textBox).X;
    int clickY = (int)e.GetPosition(textBox).Y;
    int startPosition = 0;
    double currentHeight = 0;
    double calculatedHeight = 0;
    int charIndex;

    TextBlock tb = new TextBlock();
    tb.Width = this.textBox.Width;
    tb.FontFamily = this.textBox.FontFamily;
    tb.FontSize = this.textBox.FontSize;
    for (charIndex = 0; charIndex < this.textBox.Text.Length; charIndex++)
    {
        tb.Text = this.textBox.Text.Substring(startPosition, charIndex - startPosition + 1);
        if (tb.ActualHeight > currentHeight)
        {
            if (currentHeight == 0)
            {
                currentHeight = tb.ActualHeight;
                calculatedHeight = currentHeight;
            }
            else
            {
                startPosition = charIndex + 1;
                charIndex++;
                tb.Text = this.textBox.Text.Substring(startPosition, charIndex - startPosition + 1);
                currentHeight = tb.ActualHeight;
                calculatedHeight += currentHeight;
            }
        }

        if (tb.ActualWidth > clickX && calculatedHeight > clickY) break;
    }

    _insertPoint = charIndex;

Я не буду лгать и говорить, что это элегантно, но, кажется, работает достаточно хорошо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...