There is an int property of the ‘CustomControl’ (in Silverlight 4 application), TextBlock is displayed inside of the ‘Canvas’ control:
<Canvas Name="canvas" >
<Ellipse Fill="Yellow" Canvas.Top="8" Canvas.Left="8" Height="16" Width="16">
</Ellipse>
<TextBlock Name="TeamNumberTextBlock" Text="9" Canvas.Top="8" Canvas.Left="8" TextAlignment="Center" FontStyle="Italic" />
</Canvas>
As text can be changed It should be centered. Here is a “CodeBehind-solution”:
public partial class FieldItem : UserControl
{
public FieldItem()
{
InitializeComponent();
}
public int TeamNumber
{
private get
{
return _iTeamNumber;
}
set
{
_iTeamNumber = value;
TeamNumberTextBlock.Text = _iTeamNumber.ToString();
TeamNumberTextBlock.SetValue(Canvas.LeftProperty, (TeamNumberTextBlock.Width - TeamNumberTextBlock.Width) / 2);
}
}
private int _iTeamNumber;
}
When somebody will set a new value to the control, its ‘Canvas.Left’ property will be recalculated.
Is it possible to implement similar functionality using binding (or any other mechanism that is workable in design mode)?
Thank you!
A
Canvasis probably not the ideal container for that kind of thing… you can achieve the same result with aGrid. You won’t have to recalculate the position, you just need to specify theHorizontalAlignmentandVerticalAlignmentand theTextBlockwill remain centered automatically:In a
Grid, you can specify the row and column where an element is displayed. If there is only one row and one column (which is the default), all elements appear in the same “cell”. The last element added appears on top (unless you specify thePanel.ZIndexproperty to change the Z-order)