Friday 18 November 2011

How to use the ViewBox in WPF


Introduction

The ViewBox is a very useful control in WPF. If does nothing more than scale to fit the content to the available size. It does not resize the content, but it transforms it. This means that also all text sizes and line widths were scaled. Its about the same behavior as if you set the Stretch property on an Image or Path to Uniform.
Although it can be used to fit any type of control, it's often used for 2D graphics, or to fit a scalable part of a user interface into an screen area.
<Button Content="Test" />
 
<Viewbox Stretch="Uniform">
    <Button Content="Test" />
</Viewbox>
 

Canvas Panel

 

 

Introduction

The Canvas is the most basic layout panel in WPF. It's child elements are positioned by explicit coordinates. The coordinates can be specified relative to any side of the panel usind the Canvas.Left, Canvas.Top, Canvas.Bottom and Canvas.Right attached properties.
The panel is typically used to group 2D graphic elements together and not to layout user interface elements. This is important because specifing absolute coordinates brings you in trouble when you begin to resize, scale or localize your application. People coming from WinForms are familiar with this kind of layout - but it's not a good practice in WPF.


 
<Canvas>
    <Rectangle Canvas.Left="40" Canvas.Top="31" Width="63" Height="41" Fill="Blue"  />
    <Ellipse Canvas.Left="130" Canvas.Top="79" Width="58" Height="58" Fill="Blue"  />
    <Path Canvas.Left="61" Canvas.Top="28" Width="133" Height="98" Fill="Blue" 
          Stretch="Fill" Data="M61,125 L193,28"/>
</Canvas>
 
 

Override the Z-Order of Elements

Normally the Z-Order of elements inside a canvas is specified by the order in XAML. But you can override the natural Z-Order by explicity defining a Canvas.ZIndex on the element.
 
<Canvas>
    <Ellipse Fill="Green" Width="60" Height="60" Canvas.Left="30" Canvas.Top="20"    
             Canvas.ZIndex="1"/>
    <Ellipse Fill="Blue"  Width="60" Height="60" Canvas.Left="60" Canvas.Top="40"/>
</Canvas>
 
 

No comments:

Post a Comment