开发者

Centering Text within a Silverlight Shape using a Canvas

开发者 https://www.devze.com 2023-01-25 11:10 出处:网络
I have a canvas control which I\'m housing a shape and some text in. <Canvas x:Name=\"myCanv\"> <Rectangle x:Name=\"myRect\" Stroke=\"Gray\" Fill=\"Blue\" StrokeThickness=\"3\" Width=\"675\"

I have a canvas control which I'm housing a shape and some text in.

<Canvas x:Name="myCanv">
  <Rectangle x:Name="myRect" Stroke="Gray" Fill="Blue" StrokeThickness="3" Width="675" Height="350"/>
  <TextBlock x:Name="myText"/>
</Canvas>

In my code behind i'll be changing the text as events occur and I thought it'd be neat to place the text in the center of "myRect".

I found a great blog post on how to center text in a canvas control in WPF app using MultiBinding Converters. After reading it, I tried it out for WP7 only to be met with pain!

Unfortunately, it seems as though Silverlight 4 (of which WP7 Silverlight is a subset) doesn't have MultiBinding Converters. I then found a blog which has code for MbC in SL4, but i can't open the project in VS2010 Express.

Has anyone either

A) Centered text via a value converter

or

B) 开发者_开发百科found a better way to center the text without using a value converter

...? :)


How about using a Border instead, that way you can simple set the Horizontal and Vertical Alignment properties of the TextBlock to Center.

<Border BorderBrush="Gray" Background="Blue" BorderThickness="3" Width="675" Height="350">
    <TextBlock Text="Hello" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>


You could just put the textbox outside the canvas in the visual tree but absolutely position it to the same size and location. You could then set the horizontal and vertical alignment on the textblock so that the text appears as if centered in the canvas.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号