views:

23

answers:

1

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!

+2  A: 

A Canvas is probably not the ideal container for that kind of thing... you can achieve the same result with a Grid. You won't have to recalculate the position, you just need to specify the HorizontalAlignment and VerticalAlignment and the TextBlock will remain centered automatically:

<Grid>
    <Ellipse Fill="Yellow" Height="16" Width="16">
    </Ellipse>
    <TextBlock Name="TeamNumberTextBlock" Text="9"
               HorizontalAlignment="Center"
               VerticalAlignment="Center"
               FontStyle="Italic" />
</Grid>

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 the Panel.ZIndex property to change the Z-order)

Thomas Levesque
Interesting solution, thanks.
Budda