2009-12-17 84 views

回答

5
public class AutoCompleteTextBox : TextBox 
{ 
    public Point GetPositionFromCharacterIndex(int index) 
    { 
     if (TextWrapping == TextWrapping.Wrap) throw new NotSupportedException(); 

     var text = Text.Substring(0, index); 

     int lastNewLineIndex = text.LastIndexOf('\r'); 

     var leftText = lastNewLineIndex != -1 ? text.Substring(lastNewLineIndex + 1) : text; 

     var block = new TextBlock 
         { 
          FontFamily = FontFamily, 
          FontSize = FontSize, 
          FontStretch = FontStretch, 
          FontStyle = FontStyle, 
          FontWeight = FontWeight 
         }; 

     block.Text = text; 
     double y = block.ActualHeight; 

     block.Text = leftText; 
     double x = block.ActualWidth; 

     var scrollViewer = GetTemplateChild("ContentElement") as ScrollViewer; 

     var point = scrollViewer != null 
         ? new Point(x - scrollViewer.HorizontalOffset, y - scrollViewer.VerticalOffset) 
         : new Point(x, y); 
     point.X += BorderThickness.Left + Padding.Left; 
     point.Y += BorderThickness.Top + Padding.Top; 

     return point; 
    } 
} 
2

除了altso's answer,我想提一提,你確實需要調用塊.Measure().Arrange()方法.ActualHeight.ActualWidth工作,例如,像這樣(參數可能取決於你的用例):

block.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); 
block.Arrange(new Rect(0, 0, block.DesiredSize.Width, block.DesiredSize.Height)); 
double y = block.ActualHeight; 

這是在WPF需要,和在Silverlight(包括SL5)。否則,最終WPF中的ActualHeight和Silverlight中奇怪的數字(在我的情況中,這些是圍繞的所有文本的邊界框的座標)中的0。


作爲一個獨立的解決方案,你可以使用FormattedText類做同樣的伎倆。

+0

感謝您的補充 – altso

相關問題