如何使用OnRender自定义TextBlock

时间:2014-09-07 02:59:24

标签: c# wpf xaml textblock

我无法理解......我开始认为它无法完成。

我想创建一个自定义文本块控件,允许测量包含的文本。我可以执行以下操作,因为OnRender()是密封的。但是,如果我使用 new ,我的新" OnRender()"永远不会被称为。那怎么办呢?有没有更好的办法? (CustomTextBlock在MVVM框架中的ItemsControl中使用。我不想创建任何其他依赖项属性。)

请提前通知并表示感谢。

XAML中的用法:

 <i:CustomTextBlock Grid.Row="0"  x:Name="tbc"
               Text="{Binding Text}" 
               FontSize="{Binding FontSize}" 
               FontStyle="Italic" 
               Foreground="{Binding Color}" 
               FontFamily="Segoe Script" />

控制定义:

 public class CustomTextBlock : TextBlock
{
    public CustomTextBlock() : base()
    {
    }

 // THIS FAILS...BUT "NEW" IS NEVER CALLED???
    protected override void OnRender(DrawingContext drawingContext)
    {
        base.OnRender(drawingContext);

        Typeface typeface = new Typeface(this.FontFamily,
            this.FontStyle,
            this.FontWeight,
            this.FontStretch); 

        FormattedText formmatedText = new FormattedText(
            this.Text,
            System.Threading.Thread.CurrentThread.CurrentCulture,
            this.FlowDirection,
            typeface,
            this.FontSize,
            this.Foreground);

    }
}

1 个答案:

答案 0 :(得分:0)

我无法想象OnRender,但这有助于解决我的问题。这是一个可能的解决方案,虽然不是真正的答案。

在UserControl的代码隐藏中,XAML使用x定义TextBlock:Name =“tbc”。

希望这有助于某人。

   public partial class InkStringView : UserControl
{
    public InkStringView()
    {
        InitializeComponent();           
        tbc.Loaded += new RoutedEventHandler(InkStringView_Loaded);
    }

    void InkStringView_Loaded(object sender, RoutedEventArgs e)
    {
        TextBlock tb = sender as TextBlock;

        Typeface typeface = new Typeface(
          tb.FontFamily,
          tb.FontStyle,
          tb.FontWeight,
          tb.FontStretch);

       FormattedText formattedText = new FormattedText(
            tb.Text,
            System.Threading.Thread.CurrentThread.CurrentCulture,
            tb.FlowDirection,
            typeface,
            tb.FontSize,
            tb.Foreground);

        StringViewModel svm = tb.DataContext as StringViewModel;
        svm.Bounds = formattedText.GetBoundingRect();
        svm.MidlineY1 = svm.MidlineY2 =  svm.Bounds.Top + 0.45 * (formattedText.Baseline - svm.Bounds.Top);


        double width = tb.ActualWidth;
        double height = tb.ActualHeight;

        var parent = VisualTreeHelper.GetParent(this);
        while (!(parent is Window))
        {
            parent = VisualTreeHelper.GetParent(parent);
        }


        GeneralTransform gt = tb.TransformToAncestor(parent as UIElement);
        Point offset = gt.Transform(new Point(0, 0));
        double controlTop = offset.Y;
        double controlLeft = offset.X;
    }       
}
相关问题