2011-11-15 20 views
4

我有一个richtextbox,里面有一个列表框。我希望列表框位于插入符号的下方,并随着插入符号的移动而移动。在richtextbox中定位listbox

我该怎么做?

我应该操纵前两个值listBox.Margin以及如何? 谢谢!

回答

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(); 
     } 
    } 
} 
+0

非常感谢!我正在寻找这样的东西:) – gumenimeda

+0

很高兴成为服务 –

+0

这太棒了。我查看了API,但一定错过了这个。优秀作品。 :) –

0

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

我假设解决方案将沿着将RichTextBox和ListBox放置在Canvas中,并且每当RichTextBox的文本发生更改时将ListBox放置在Caret位置。

但是,我不知道如何检索脱字符的位置。 :/

+0

是的,我一直想了一会儿:/谢谢你的文章! – gumenimeda