Content by Category
.NET 1.x
.NET 2.0
.NET 3.0
.NET 3.5
.NET 4.0
.NET 4.5
.NET Assemblies
.NET Framework
.NET Getting Started
Accessibility
ADO.NET
Advertorials
Agile Development
AJAX
Amazon Web Services
Analysis Services
Android
Architecture
Arduino
ASP .NET Web API
ASP.NET
ASP.NET MVC
ASP.NET WebForms
Azure
B2B (Business Integration)
BDD
Big Data
Bing
BizTalk
Book Excerpts
Build and Deploy
Business Intelligence
C#
C++
ClickOnce
Cloud Computing
Code Contracts
CODE Framework Info - non Technical
CODE on the Road!
COM+
Community
Conferences
Continuous Integration
Crystal Reports
CSLA.NET
CSS
Data
Debugger
Design Patterns
Development Process
Display Technologies
Distributed Computing
Document Database
DotNetNuke
DSL
Dynamic Languages
Dynamic Programming
Editorials
Enterprise Services ("COM+")
Entity Framework
Events
Expression Blend
F#
Fox to Fox
Frameworks
Functional Programming
Git
Graphics
HTML 5
Internet Explorer 8.0
Interviews
IOS
iPhone
Iron Ruby
Java
Java Script
JavaScript
jQuery
JSON
Lightswitch
LINQ
Linux
LUA
Mac OS X
MDX
Messaging
Metro
Microsoft Application Blocks
Microsoft Business Rules Framework
Microsoft Dynamics
Microsoft Expression
Microsoft Office
Mobile Development
Mobile PC
Mono
MsBuild
MVVM
MySQL
Network
NHibernate
node.js
NOSQL
Nuget
Object Oriented Development
Objective C
Odata
OLAP
Open Source
Opinion
Opinions
Oracle
ORM
Other Languages
Parallel Programming
Patterns
PHP
Podcasts
Post Mortem
PowerPoint
Print/Output
Prism
Product News
Product Reviews
Project Management
Prolog
Python
Q&A
Rails
Rake
Razor
Reporting Services
REST
RIA Services
Ruby
Ruby on Rails
Scheme
Search
Security
Services
SharePoint
SignalR
Silverlight
SOA
Social Networks
Software & Law
Software Business
Source Control
Speech-Enabled Applications
SQL Server
SQL Server 2000
SQL Server 2005
SQL Server 2008
SQL Server 2012
SQL Server CE/AnyWhere/Mobile/Compact
SSIS
Subversion
Sync Framework
Tablet PC
TDD
Team System
Techniques
Testing and Quality Control
TFS
Tips
TypeScript
UI Design
UML
User Groups
VB Script
VB.NET
Version Control
VFP and .NET
VFP and SQL Server
Virtual Earth
Vista
Visual Basic
Visual Basic 6 (and older)
Visual FoxPro
Visual Studio .NET
Visual Studio 11
Visual Studio 2005
Visual Studio 2008
Visual Studio 2010
Visual Studio 2011
Visual Studio 2012
Visual Studio Tools for Office
VSX
WCF
Web Development (general)
Web Services
WebMatrix
WF
Whitepapers
Windows 7
Windows 8
Windows Azure
Windows Live
Windows Phone 7
Windows Phone SDK
Windows Server
Windows Vista
WinForms
WinRT
Workflow
WPF
XAML
Xiine Documentation
XML
XNA
XSLT



LearnNow


XAMALOT
 


SSWUG

Reader rating:
Article source: CoDe (2010 Jul/Aug)


Article Pages:  1  2 3 - Next >


Centering Text on a WPF Shape Using a User Control

WPF excels at creating great looking applications.

One of the ways you can make your application look great is to add some shapes like circles, triangles and rectangles. However, the shapes in WPF do not allow you to add text (or any content) within the shape, as shapes are not containers.

In a WPF application I am building right now, I have a need to create different shapes and center text within those shapes. The shapes I need are rectangles, circles, ellipses and triangles. The problem is WPF shapes are not containers so you cannot add any text inside of them, but WPF is flexible enough that there are often several ways to work around this. In this article, I will show you a few different methods of centering text in each of these shapes.

Drawing an Ellipse/Circle Using a Border

If you wish to put text into an ellipse or a circle, you can simulate this using a Border control and play with the Width, Padding and CornerRadius properties of the Border control. I used the code snippet below to draw text within an ellipse as shown in Figure 1.

Click for a larger version of this image.

Figure 1: Use a Border control to simulate an ellipse.

<Border CornerRadius="50"
        Width="60"
        Margin="10"
        Padding="4"
        Background="Aquamarine"
        BorderBrush="Black"
        BorderThickness="1">
   <TextBlock HorizontalAlignment="Center"
              Text="Test" />
</Border>

You can set the width and height of the Border control to create a circle as well. The XAML in the next snippet creates a circle with text in the middle, as shown in Figure 2.

Click for a larger version of this image.

Figure 2: Use a Border control to simulate a circle.

<Border CornerRadius="50"
        Width="60"
        Height="60"
        Margin="10"
        Padding="0,20,0,0"
        Background="Aquamarine"
        BorderBrush="Black"
        BorderThickness="1">
   <TextBlock HorizontalAlignment="Center"
              Text="Test" />
</Border>

Draw a Triangle Using a Visual Brush

To create a triangle shape in WPF you use a Polygon control. If you remember your high school math, a Polygon is a series of connected lines that have the same start and end point. The XAML below creates a triangle; however, there is no text in it because a Polygon is not a container.

<Polygon Points="25,0 5,30 45,30"
         Fill="LightBlue"
         Stroke="Black"
         StrokeThickness="2" />

To add text like that shown in Figure 3, you need to use the Polygon control as the background of a TextBlock control. The XAML shown in Listing 1 is used to create Figure 3.

Click for a larger version of this image.

Figure 3: Use a Visual Brush to put text in a triangle.

Two key things make this XAML work. First, you use the VisualBrush object of the Background of the TextBlock object to give you a place to put the Polygon control. Second, depending on the text that you fill into the TextBlock control, and the width and height of the TextBlock control, you will need to play with the Padding property to align the text to the correct location. Take the above XAML and put it in a new window and then adjust the height, width and text values. You will see that you need to adjust the Padding property to make the text fall into the correct location within the Polygon.

Listing 2 shows another example of a Visual Brush, this time using an Ellipse control. Figure 4 shows the results of the XAML in Listing 2.

Click for a larger version of this image.

Figure 4: Use a Visual Brush to put text in an ellipse.

Notice the Padding attribute is different than when using the Polygon control. You will need to make minor adjustments based on the shape that you are using and the height and width of the control, and the text you are putting into the TextBlock.

Position a Shape on a Canvas

Using a Visual Brush within a TextBlock control works, but it is not very re-usable code. The ultimate goal of this article is to show you how to move all of this code into one user control that you can use over and over again. Before you can learn that technique, you first need to learn to use a Canvas, a Shape, a TextBlock and MultiBinding converters.

You use a WPF Canvas control to position child controls at a specified point on the Canvas. I created Figure 5 by placing a shape (you can use any control) at a certain point by setting the attached properties “Canvas.Top” and “Canvas.Left”. In Figure 5 you can see that the circle is positioned 20 points below the top of the Canvas and 40 points to the right of the Canvas’ leftmost border. I used the XAML below to create Figure 5.

Click for a larger version of this image.

Figure 5: Position the circle at a specific point on a Canvas.

<Canvas Name="cnvMain"
        Width="80"
        Height="80">
  <Ellipse Canvas.Top="20"
           Canvas.Left="40"
           Width="40"
           Height="40"
           Fill="Gray" />
</Canvas>

Place a Shape within a Canvas

Most of the time, you want a shape to take up the same amount of width and height as the Canvas. So, you can simply set the Width and Height properties of both the Canvas control and the Shape control to be exactly the same. Since the Shape control is the child within the Canvas, it will fill up the whole Canvas. Note that you do not need to specify the Canvas.Top and Canvas.Left as the default for these is zero (0) for any child control placed in a Canvas as shown in the following XAML.

<Canvas Name="cnvMain"
        Width="80"
        Height="80">
  <Ellipse Width="80"
           Height="80"
           Fill="Gray" />
</Canvas>

Bind Ellipse Width and Height to Canvas

The problem with the above XAML is that if you wish to change the width and the height of the Canvas and you want the shape to be the exact same height, you need to change four numbers. Instead of hard-coding the numbers on the Shape control, you can take advantage of the element-to-element binding features of WPF. Below is an example of binding the Width and Height of the ellipsis to the Width and Height of the Canvas. The XAML below will produce the circle shown in Figure 6.

Click for a larger version of this image.

Figure 6: A circle bound to the same height and width as the Canvas on which it is placed.

<Canvas Name="cnvMain"
        Width="80"
        Height="80">
  <Ellipse 
       Width="{Binding ElementName=cnvMain, 
                       Path=ActualWidth}"
       Height="{Binding ElementName=cnvMain,
                        Path=ActualHeight}"
       Fill="Gray" />
</Canvas>
&

By: Paul D. Sheriff

Paul D. Sheriff is the President of PDSA, Inc. (www.pdsa.com), a Microsoft Partner in Southern California. Paul acts as the Microsoft Regional Director for Southern California assisting the local Microsoft offices with several of their events each year and being an evangelist for them. Paul has authored several books, webcasts, videos and articles on .NET, SQL Server and SharePoint. You can reach Paul via email at PSheriff@pdsa.com or at Paul Sheriff’s Inner Circle (www.PaulSheriffInnerCircle.com).

PSheriff@pdsa.com



Listing 1: Place Text in a Triangle using a Visual Brush
<TextBlock Text="Test"
           Width="50"
           Height="50"
           Padding="13,28,0,0">
   <TextBlock.Background>
     <VisualBrush>
       <VisualBrush.Visual>
          <Polygon Points="25,0 5,30 45,30"
                   Fill="LightBlue"
                   Stroke="Black"
                   StrokeThickness="2" />
       </VisualBrush.Visual>
     </VisualBrush>
   </TextBlock.Background>
</TextBlock>


Listing 2: Place Text in an Ellipse using a Visual Brush
<TextBlock Text="Test"
           Height="40"
           Width="40"
           Padding="8,10,0,0">
  <TextBlock.Background>
    <VisualBrush>
      <VisualBrush.Visual>
         <Ellipse Height="20"
                  Width="20"
                  Fill="LightBlue" />
      </VisualBrush.Visual>
    </VisualBrush>
  </TextBlock.Background>
</TextBlock>


Article Pages:  1  2 3 - Next Page: 'Page 2' >>


How would you rate the quality of this article?
1 2 3 4 5
Poor      Outstanding

Tell us why you rated the content this way. (optional)

Average rating:
5 out of 5

6 people have rated this article.

Instantly Search Terabytes Of Text
“Lightning Fast”
– Redmond Mag
“Covers all data
sources” – eWeek
25+ fielded & full-text search options
dtSearch’s own document filters highlight hits in popular file types
Web Spider supports static & dynamic data
APIs for .NET, Java, C++, SQL, etc.
Win / Linux (64-bit & 32-bit)
www.dtSearch.com
 

      Sharepoint TechCon

 

SSWUG