class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Media;
namespace WpfApplication25
{
public class MyTextBlock : FrameworkElement
{
TextBlock t;
public MyTextBlock()
{
t = new TextBlock()
{
Text = "TextTextText",
Background = Brushes.Blue,
Width = 60,
Height = 30
};
AddLogicalChild(t);
AddVisualChild(t);
}
protected override Size MeasureOverride(Size availableSize)
{
t.Measure(availableSize);
return base.MeasureOverride(availableSize);
}
protected override Size ArrangeOverride(Size finalSize)
{
t.Arrange(new Rect(new Point(50, 50), t.DesiredSize));
return base.ArrangeOverride(finalSize);
}
// In order for the visual tree to be enumerated correctly,
// we must override the GetVisualChild and VisualChildrenCount.
protected override Visual GetVisualChild(int index)
{
return t;
}
protected override int VisualChildrenCount
{
get
{
return 1;
}
}
}
}
Xaml :
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Media;
namespace WpfApplication25
{
public class MyTextBlock : FrameworkElement
{
TextBlock t;
public MyTextBlock()
{
t = new TextBlock()
{
Text = "TextTextText",
Background = Brushes.Blue,
Width = 60,
Height = 30
};
AddLogicalChild(t);
AddVisualChild(t);
}
protected override Size MeasureOverride(Size availableSize)
{
t.Measure(availableSize);
return base.MeasureOverride(availableSize);
}
protected override Size ArrangeOverride(Size finalSize)
{
t.Arrange(new Rect(new Point(50, 50), t.DesiredSize));
return base.ArrangeOverride(finalSize);
}
// In order for the visual tree to be enumerated correctly,
// we must override the GetVisualChild and VisualChildrenCount.
protected override Visual GetVisualChild(int index)
{
return t;
}
protected override int VisualChildrenCount
{
get
{
return 1;
}
}
}
}
Xaml :
<Window x:Class="WpfApplication25.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300"
xmlns:local="clr-namespace:WpfApplication25">
<Grid>
<local:MyTextBlock></local:MyTextBlock>
</Grid>
</Window>
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300"
xmlns:local="clr-namespace:WpfApplication25">
<Grid>
<local:MyTextBlock></local:MyTextBlock>
</Grid>
</Window>