在RichTextBox中定位ListBox

4
我有一个 richTextbox,在里面有一个 listBox。我想让 listBox 位于光标正下方并随着光标移动而移动。
我该如何做?
我应该操纵 listBox.Margin 的前两个值,怎么做呢?谢谢!
2个回答

4
这是我会做的事情(将我的矩形替换为您的列表框):
<Window
    x:Class="Wpf_Playground.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow"
    Height="350"
    Width="525">
    <Grid>
        <RichTextBox
            Margin="0,0,0,32"
            x:Name="rtb"
            SpellCheck.IsEnabled="True"
            SelectionChanged="RtbSelectionChanged"
            TextChanged="RtbTextChanged">
        </RichTextBox>
        <Rectangle
            x:Name="rect"
            Width="30"
            Height="30"
            Fill="#80000000"
            VerticalAlignment="Top"
            HorizontalAlignment="Left"
            IsHitTestVisible="False"/>
        <TextBlock
            x:Name="tb"
            Margin="0"
            VerticalAlignment="Bottom" />
    </Grid>
</Window>

using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;

namespace Wpf_Playground
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="MainWindow"/> class.
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();
        }

        private void RtbSelectionChanged(object sender, RoutedEventArgs e)
        {
            this.UpdateCaretInfo();
        }

        /// <summary>
        /// The update caret info.
        /// </summary>
        private void UpdateCaretInfo()
        {
            var caretRect =
                rtb.CaretPosition.GetCharacterRect(LogicalDirection.Forward);
            tb.Text = caretRect.ToString();

            rect.Margin = new Thickness(
                caretRect.Right, 
                caretRect.Bottom, 
                -caretRect.Right, 
                -caretRect.Bottom);
        }

        private void RtbTextChanged(object sender, TextChangedEventArgs e)
        {
            this.UpdateCaretInfo();
        }
    }
}

非常感谢!我一直在寻找这样的东西 :) - gumenimeda
太棒了。我看了一下API,但可能错过了这个。做得很好。 :) - cwharris

0

我不确定如何获取插入符的位置(虽然这是一个非常好的问题,我很想知道如何解决),但我知道RichTextBox不能包含子元素。

我猜解决方案可能是将RichTextBox和ListBox放在Canvas中,并在每次RichTextBox文本更改时将ListBox定位到插入符的位置。

但是,我仍然不知道如何检索插入符的位置。 :/


是的,我已经尝试了一段时间:/ 感谢您的帖子! - gumenimeda

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接