Using XAML ViewBox in WPF

The XAML ViewBox element represents a view box control that is used to stretch and scale a single child item to fill the available space. This article shows how to use a ViewBox in WPF.

Creating a ViewBox

The Viewbox element represents a WPF ViewBox control in XAML.

  1. <Viewbox /> 

Viewbox has a Stretch property that defines how contents are fit in the space and its value can be Fill, None, Uniform or UniformToFill.

The code snippet in Listing 1 creates a Viewbox control and sets its stretch to fill. The output looks as in Figure 1 where the child control is filled in the Viewbox area.

  1. <Viewbox Height="200" HorizontalAlignment="Left" Margin="19,45,0,0"   
  2.          Name="viewbox1" VerticalAlignment="Top" Width="300"  
  3.          Stretch="Fill">  
  4.     <Ellipse Width="100" Height="100" Fill="Red" />      
  5. </Viewbox>

                                                       Listing 1

The output looks as in Figure 1.

   output looks
                                                      Figure 1

Creating a ViewBox Dynamically

The following code snippet creates a Viewbox at run-time.

  1. private void CreateViewboxDynamically()  
  2. {  
  3.     Viewbox dynamicViewbox = new Viewbox();  
  4.     dynamicViewbox.StretchDirection = StretchDirection.Both;  
  5.     dynamicViewbox.Stretch = Stretch.Fill;  
  6.     dynamicViewbox.MaxWidth = 300;  
  7.     dynamicViewbox.MaxHeight = 200;  
  8.   
  9.     Ellipse redCircle = new Ellipse();  
  10.     redCircle.Height = 100;  
  11.     redCircle.Width = 100;  
  12.     redCircle.Fill = new SolidColorBrush(Colors.Red);  
  13.     dynamicViewbox.Child = redCircle;  
  14.   
  15.     RootLayout.Children.Add(dynamicViewbox);  

Summary

In this article, I discussed how to create a ViewBox control in Silverlight and C#.

Up Next
    Ebook Download
    View all
    Learn
    View all