top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Using XAML Expander in WPF

+3 votes
1,624 views

The WPF Expander represents a control with an expanded view where the contents of the expanded area can be expanded or collapsed.

The following XAML code shows how to create an Expander control in WPF.

<Expander Name="ExpanderControl" Header="Click to Expand"   
          HorizontalAlignment="Left" >  
    <TextBlock TextWrapping="Wrap" FontSize="14" FontWeight="Light" Foreground="Black">  
        This is an Expander control. Within this control, all contents will be wrapped.  
        At run-time, you may expand or collapse this control. Type more text here to be typed.  
        Jump around and hype.   
    </TextBlock>  
</Expander> 

The default view of an Expander control looks like this.


If you click on the header, the expanded view looks like this.



Most of the time, you would want the header of the Expander control to look different from the contents. This can be done by simply setting the font properties of the Expander control different from the contents.
 

This code sets the FontSize and FontWeight of the Expander control different from the contents of the Expander control. 

<Window x:Class="ExpanderControlSample.Window1"  
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
        Title="Window1" Height="300" Width="300">  
    <Grid>  
        <Expander Name="ExpanderControl" Background="LavenderBlush"   
          HorizontalAlignment="Left" Header="Click to Expand"   
          ExpandDirection="Down" IsExpanded="False" Width="200"  
                  FontSize="20" FontWeight="Bold" Foreground="Green">  
            <TextBlock TextWrapping="Wrap" >  
                This is an Expander control. Within this control, all contents will be wrapped.  
                At run-time, you may expand or collapse this control. Type more text here to be typed.  
                Jump around and hype.   
            </TextBlock>  
        </Expander>  
    </Grid>  
</Window> 

The new output looks like this. As you can see from this figure, the header of the Expander control is different from the contents.


How to create an Expander control dynamically

The Expander class in WPF represents an Expander control.

This code snippet creates an Expander control at run-time.

private void CreateDynamicExpander()  
{  
   Expander dynamicExpander = new Expander();  
   dynamicExpander.Header = "Dynamic Expander";  
   dynamicExpander.HorizontalAlignment = HorizontalAlignment.Left;  
   dynamicExpander.Background = new SolidColorBrush(Colors.Lavender);  
   dynamicExpander.Width = 250;  
   dynamicExpander.IsExpanded = false;  
   dynamicExpander.Content = "This is a dynamic expander";  
  
   RootGrid.Children.Add(dynamicExpander);  

How to set the direction of an Expander Control
 

The ExpandDirection property of the Expander control sets the direction of the Header. It can be Up, Down, Left or Right. The following code snippet sets the ExpandDirection to Up.

<Expander Name="ExpanderControl" Background="LavenderBlush"   
          HorizontalAlignment="Left" Header="Click to Expand"   
          ExpandDirection="Up" IsExpanded="False" Width="200"  
                  FontSize="20" FontWeight="Bold" Foreground="Green">  
     <TextBlock TextWrapping="Wrap" >  
         This is an Expander control. Within this control, all contents will be wrapped.  
         At run-time, you may expand or collapse this control. Type more text here to be typed.  
         Jump around and hype.   
     </TextBlock>  
</Expander>

The control with Up direction looks like this.


How to set an image in an Expander Header

Expander.Header property may be used to style the header of an Expander control. Within the Header, you can set whatever contents you would like including an Image.
 

This code adds in image and text in the header of an Expander.

<Expander Name="ExpanderControl"   
  HorizontalAlignment="Left" Background="LavenderBlush"   
  ExpandDirection="Down"  IsExpanded="False" Width="250"  
          FontSize="20" FontWeight="Bold" Foreground="Green" >  
    <Expander.Header>  
        <BulletDecorator>  
            <BulletDecorator.Bullet>  
                <Image Width="50" Source="Flowers.jpg"/>  
            </BulletDecorator.Bullet>  
            <TextBlock Margin="20,0,0,0">Flower Header</TextBlock>  
        </BulletDecorator>  
    </Expander.Header>  
  
    <TextBlock TextWrapping="Wrap" FontSize="14" FontWeight="Light" Foreground="Black">  
        This is an Expander control. Within this control, all contents will be wrapped.  
        At run-time, you may expand or collapse this control. Type more text here to be typed.  
        Jump around and hype.   
    </TextBlock>  
</Expander>  

The control with an image header looks like this.


How to add scrolling to an Expander Control
 

Adding a Scrollviewer control in the contents of an Expander adds scrolling to the Expander. This code adds scrolling to the contents of an Expander. 

<Expander Name="ExpanderControl"   
  HorizontalAlignment="Left" Background="LavenderBlush"   
  ExpandDirection="Down"  IsExpanded="False" Width="250"  
          FontSize="20" FontWeight="Bold" Foreground="Green" >  
    <Expander.Header>  
        <BulletDecorator>  
            <BulletDecorator.Bullet>  
                <Image Width="50" Source="Flowers.jpg"/>  
            </BulletDecorator.Bullet>  
            <TextBlock Margin="20,0,0,0">Flower Header</TextBlock>  
        </BulletDecorator>  
    </Expander.Header>  
    <Expander.Content>  
        <ScrollViewer Height="100" VerticalAlignment="Top" >  
            <TextBlock TextWrapping="Wrap" FontSize="14" FontWeight="Light" Foreground="Black">  
                This is an Expander control. Within this control, all contents will be wrapped.  
                At run-time, you may expand or collapse this control. Type more text here to be typed.  
                Jump around and hype. This is an Expander control. Within this control, all contents will be wrapped.  
                At run-time, you may expand or collapse this control. Type more text here to be typed.  
                Jump around and hype.  
            </TextBlock>  
        </ScrollViewer>  
    </Expander.Content>  
</Expander> 

The Expander control with a scroll viewer looks like this.

posted Mar 28, 2016 by Jdk

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button


Related Articles

The WPF Frame control using XAML and C# supports content navigation within content. A Frame can be hosted within a WindowNavigationWindowPageUserControl, or a FlowDocument control.

How to create a Frame in WPF

This XAML code shows how to create a Frame control and sets its Source property to load a XAML page within it.

  1. <Window x:Class="FrameSample.Window1"  
  2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  4.     Title="Window1" Height="300" Width="300">  
  5.     <Grid>          
  6.         <TextBlock>Outside area of frame</TextBlock>  
  7.         <Frame Source="Page1.xaml">              
  8.         </Frame>  
  9.     </Grid>  
  10. </Window>  

The Window looks like this. The Purple area is the Page1.xaml and the White area is outside of the frame.



Now you can manage the contents of a frame the way you want.

For example, the following code rotates the contents of the frame to a 45 degree angle.

  1. <Frame Source="Page1.xaml">  
  2.     <Frame.LayoutTransform>  
  3.         <RotateTransform Angle="45" />  
  4.     </Frame.LayoutTransform>  
  5. </Frame>  

The new output looks like this.



How to Navigate to a URI in a WPF Frame

The following code creates a Frame within a window and adds a button control to the window. On the button click event handler we will navigate to a URI using a Frame.

  1. <Window x:Class="FrameSample.Window1"  
  2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  4.     Title="Window1" Height="300" Width="300">  
  5.     <Grid>  
  6.         <TextBlock>Outside area of frame</TextBlock>  
  7.         <Frame Name="FrameWithinGrid" >  
  8.         </Frame>  
  9.         <Button Height="23" Margin="114,12,25,0"   
  10.                 Name="button1" VerticalAlignment="Top" Click="button1_Click">Navigate to C# Corner  
  11.         </Button>  
  12.     </Grid>  
  13. </Window>  

The Navigate method of Frame is used to navigate to a URI. The following code navigates to Page1.xaml.

  1. private void button1_Click(object sender, RoutedEventArgs e)  
  2. {  
  3.     FrameWithinGrid.Navigate(new System.Uri("Page1.xaml",  
  4.              UriKind.RelativeOrAbsolute));  
  5. }  

The following code navigates to an external website URL and opens the ASPX page within a Frame.

  1. FrameWithinGrid.Source = new Uri("http://www.c-sharpcorner.com/Default.aspx", UriKind.Absolute);  

If you need to open a URI in a new browser window, the following code will do that. This code first creates a NavigationWindow and then sets its Source to a URI.

  1. NavigationWindow window = new NavigationWindow();  
  2. Uri source = new Uri("http://www.c-sharpcorner.com/Default.aspx", UriKind.Absolute);  
  3. window.Source = source; window.Show();  
READ MORE

We can use the Line XAML element to draw lines in XAML and the Line class in WPF represents the XAML Line element. Learn here how to draw a Line in WPF. In this article, we will see how to use the LineSegment to draw a line. 

 

Besides drawing lines using the Line element, we can also use the LineSegment element. The LineSegment is useful when a line becomes a part of a graphics path or a larger geometric object. 

 

The LineSegment object represents a line between a start point and an end point. The LineSegment class has one property, Point that represents the end point of the line. The start point is a part of the path. 

 

The following XAML code snippet creates a line segment. A Path object is used to draw an arc by setting a PathGeomerty as Path.Data. 

 

<Path Stroke="Black" StrokeThickness="1">
    <Path.Data>
        <PathGeometry>
            <PathGeometry.Figures>
                <PathFigureCollection>
                    <PathFigure StartPoint="0,100">
                        <PathFigure.Segments>
                            <PathSegmentCollection>
                                <LineSegment Point="200,100" />
                            </PathSegmentCollection>
                        </PathFigure.Segments>
                    </PathFigure>
                </PathFigureCollection>
            </PathGeometry.Figures>
        </PathGeometry>
    </Path.Data>
</Path>

 

The following code snippet creates a Path and sets a LineSegment as a part of PathFigure.Segments.The output looks like Figure 1. 

 

LineSegment.jpg

 

Figure 1 

 

The following code snippet dynamically creates the line segment shown in Figure 1.

 

private void CreateLineSegment()
{
    PathFigure pthFigure = new PathFigure();
    pthFigure.StartPoint = new Point(10, 100);
    LineSegment lineSeg = new LineSegment ();
    lineSeg.Point = new Point(200, 100);  

    PathSegmentCollection myPathSegmentCollection = new PathSegmentCollection();
    myPathSegmentCollection.Add(lineSeg); 

    pthFigure.Segments = myPathSegmentCollection; 

    PathFigureCollection pthFigureCollection = new PathFigureCollection();
    pthFigureCollection.Add(pthFigure);
    PathGeometry pthGeometry = new PathGeometry();
    pthGeometry.Figures = pthFigureCollection; 

    Path arcPath = new Path();
    arcPath.Stroke = new SolidColorBrush(Colors.Black);
    arcPath.StrokeThickness = 1;
    arcPath.Data = pthGeometry;
    arcPath.Fill = new SolidColorBrush(Colors.Yellow); 

    LayoutRoot.Children.Add(arcPath);

}

READ MORE

In this article, I will try to make a representation of the Grid object witch is directly derived from the Panel abstract class and we can say that is a flexible area that contains rows and columns, it plays a role of container in a given WPF window. The grid could be found in the PresentationFramework assembly. The grid control could be used to create a complex layout that gives to the application an attractive and ergonomic look. So let's discover how to configure it using XAML in this part and in second part I will illustrate how to perform the same task using the code behind, I mean C#.

At first look, when a new WPF application is defined, we have the impression that there is not controls but the window one, even if the "<Grid></Grid>" tags are presents, and the first question that one can ask is where are the grid lines if it is a grid really? 

 

Figure 1

I tell you ok try this code:

<Grid ShowGridLines="True">

        <Grid.RowDefinitions>

            <RowDefinition></RowDefinition>

            <RowDefinition></RowDefinition>

            <RowDefinition></RowDefinition>

        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>

            <ColumnDefinition></ColumnDefinition>

            <ColumnDefinition></ColumnDefinition>

            <ColumnDefinition></ColumnDefinition>

        </Grid.ColumnDefinitions>       

    </Grid>

I use the <Grid.RowDefinitions> to define a collection of rows and a<Grid.ColumnDefinitions> to define columns collection. In the other hand I use<RowDefinition> to define a row element within the grid control and <ColumnDefinition> to define a column element, and then I set ShowGridLines property to true, it is very important in order to render columns and rows visible. The result will be as follows:

Figure 2

The columns and rows definition mode could be, namely star, Auto or Pixel.

The Star definition

It means that the related size could be expressed as weighted proportion of available space, for example if a size of a given first row is double of a second given row size, then the first one will receive two units of the entire grid size, meanwhile, the second one will have one unit as size. Rows and columns sizes are expressed by this symbol * that represents a unit of size. The XAML code sample illustrates how to define a size based on star definition.

<Grid ShowGridLines="True" >

        <Grid.RowDefinitions>

            <RowDefinition></RowDefinition>

            <RowDefinition></RowDefinition>

            <RowDefinition></RowDefinition>

        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>

            <ColumnDefinition Width="2*"></ColumnDefinition>

            <ColumnDefinition></ColumnDefinition>

            <ColumnDefinition></ColumnDefinition>

        </Grid.ColumnDefinitions>       

    </Grid>

The result of the above code is:

Figure 3

The above code sets the first column width as double of the reset of the columns.

The Pixel definition

It means that the size is defined in terms of pixels such as in the ASP applications. This bellow code illustrate how to define a dimension of a given column or row based on pixels

<Grid ShowGridLines="True" >

        <Grid.RowDefinitions>

            <RowDefinition></RowDefinition>

            <RowDefinition></RowDefinition>

            <RowDefinition></RowDefinition>

        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>

            <ColumnDefinition Width="100px"></ColumnDefinition>

            <ColumnDefinition></ColumnDefinition>

            <ColumnDefinition></ColumnDefinition>

        </Grid.ColumnDefinitions>       

    </Grid>

And this is a presentation of what could be if such alternative is used

Figure 4

The Auto definition

It means that the size is proportional to the content object size. Once the column or the row width or height is set to auto and there is no object contained with it. It disappears from the grid but it doesn't mean that it is deleted. If you add controls within, it takes exactly the control dimension. For example, if we make a rectification of the previous code

<Grid ShowGridLines="True" >

        <Grid.RowDefinitions>

            <RowDefinition></RowDefinition>

            <RowDefinition></RowDefinition>

            <RowDefinition></RowDefinition>

        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>

            <ColumnDefinition Width="Auto"></ColumnDefinition>

            <ColumnDefinition></ColumnDefinition>

            <ColumnDefinition></ColumnDefinition>

        </Grid.ColumnDefinitions>       

    </Grid>

The grid appearance will be

Figure 5

Cut  Width="Auto"  then drag and drop a button into the grid and make sure that it is contained within the row 0 , column 0 grid cellule and this is the XAML button code.

<Button Grid.Column="0" Grid.Row="0" Width="100" Name="button1">Button</Button>

Now, paste Width="Auto" exactly in its previous place and you will observe this. As you see the button is clipped rather that scrolled.

Figure 6

 

READ MORE

XAML RepeatButton in WPF

XAML RepeatButton represents a set of repeat buttons. This article shows how to use a RepeatButton control in WPF using XAML and C#. 

Creating a RepeatButton

The RepeatButton XAML element represents a WPF RepeatButton control. 

  1. <Button/>  

The Width and Height attributes represent the width and the height of a RepeatButton. The Content property sets the text of the button. The Name attribute represents the name of the control, that is a unique identifier of a control. 

The code snippet in Listing 1 creates a Button control and sets its name, height, width and content. 


<RepeatButton Margin="10,10,0,0" VerticalAlignment="Top"   
   HorizontalAlignment="Left"   
   Name="GrowButton" Width="80" Height="30">  
</RepeatButton>  

Listing 1

The default property of a button is Content. The code snippet in Listing 2 creates the same button as created by Listing 1.

<RepeatButton Margin="10,10,0,0" VerticalAlignment="Top"   
   HorizontalAlignment="Left"   
   Name="GrowButton" Width="80" Height="30">  
   Grow  
</RepeatButton>  

Listing 2

The output looks as in Figure 1



Figure 1

Delay and Interval

The Delay and Interval properties make a RepeatButton different from a normal button. 

RepeatButton is a button that fires Click events repeatedly when it is pressed and held. The rate and aspects of repeating are determined by the Delay and Interval properties that the control exposes.

The code snippet in Listing 3 sets the Delay and Interval properties. 


<RepeatButton Margin="10,10,0,0" VerticalAlignment="Top"   
   HorizontalAlignment="Left"   
   Name="GrowButton" Width="80" Height="30"   
   Delay="500" Interval="100" >  
   Grow  
</RepeatButton>  

Listing 3

Adding a Button Click Event Handler

The Click attribute of a RepeatButton element adds the click event handler and it keeps firing the event for the given Interval and delay values. The code in Listing 4 adds the click event handler for a Button. 

<Button x:Name="DrawCircleButton" Height="40" Width="120"   
        Canvas.Left="10" Canvas.Top="10"   
        Content="Draw Circle"  
        VerticalAlignment="Top"   
        HorizontalAlignment="Left">  
Click="DrawCircleButton_Click"  
</Button>  

Listing 4

The code for the click event handler looks as in following. 

  1. private void GrowButton_Click(object sender, RoutedEventArgs e)  
  2. {  
  3. }  

Okay, now let's write a useful application. 

We will build an application with the two buttons Grow and Shrink and a rectangle. The application looks as in Figure 2.

When you click and continue pressing the Grow button, the width of the rectangle will continue to grow and when you click on the Shrink button, the width of the rectangle will shrink continuously. 



Figure 2

The final XAML code is listed in Listing 5

<Window x:Class="RepeatButtonSample.Window1"  
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
    Title="Window1" Height="300" Width="300">  
      
    <Grid Name="LayoutRoot">  
        <RepeatButton Margin="10,10,0,0" VerticalAlignment="Top"   
                      HorizontalAlignment="Left"                         
                      Name="GrowButton"  Width="80" Height="30"   
                      Delay="500" Interval="100"   
                      Click="GrowButton_Click">  
            Grow  
        </RepeatButton>  
        <RepeatButton Margin="100,10,0,0" VerticalAlignment="Top"   
                      HorizontalAlignment="Left"                         
                      Name="ShrinkButton"  Width="80" Height="30"   
                      Delay="500" Interval="100"   
                      Click="ShrinkButton_Click">  
            Shrink  
        </RepeatButton>  
          
        <Rectangle Name="Rect" Height="100" Width="100" Fill="Orange"/>  
  
    </Grid>  
</Window>  

Listing 5

Listing 6
 is the click event handlers for the buttons that change the width of the rectangle.

private void GrowButton_Click(object sender, RoutedEventArgs e)  
{  
    Rect.Width += 10;  
}  
  
private void ShrinkButton_Click(object sender, RoutedEventArgs e)  
{  
   

Listing 6

READ MORE

The GroupBox element in XAML is used to add a header to an area and within that area you can place controls. By default, a GroupBox can have one child but multiple child controls can be added by placing a container control on a GroupBox such as a Grid or StackPanel.

How to create a GroupBox in WPF and Windows phone application,.

The GroupBox element in XAML represents a GroupBox control. The following code snippet creates a GroupBox control and sets its background and font. The code also sets the header using GroupBox.Header. 

  1. <Window x:Class="GroupBoxSample.Window1"  
  2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  4.     Title="Window1" Height="300" Width="300">  
  5.     <Grid>  
  6.         <GroupBox Margin="10,10,10,10" FontSize="16" FontWeight="Bold"  
  7.                   Background="LightGray">  
  8.             <GroupBox.Header>                  
  9.                Mindcracker Network  
  10.             </GroupBox.Header>   
  11.               
  12.             <TextBlock FontSize="12" FontWeight="Regular">  
  13.                 This is a group box control content.                  
  14.             </TextBlock>               
  15.            
  16.         </GroupBox>  
  17.   
  18.     </Grid>  
  19. </Window>  

The output looks like this.

READ MORE

Introduction 

The RichTextBox control allows you to view and edit text, paragraph, images, tables and other rich text format contents. 

The RichTextBox tag represents a RichTextBox control in XAML. 

<RichTextBox></RichTextBox>  

The Width and Height properties represent the width and the height of a RichTextBox. The Name property represents the name of the control, that is a unique identifier of a control. The Margin property tells the location of a RichTextBox on the parent control. The HorizontalAlignment andVerticalAlignment properties are used to set horizontal and vertical alignments. 

The following code snippet sets the name, height and width of a RichTextBox control. The code also sets the horizontal alignment to left and the vertical alignment to top. 

<RichTextBox Margin="10,10,0,13" Name="RichTextBox1" HorizontalAlignment="Left"   

                 VerticalAlignment="Top" Width="500" Height="300" />  

Displaying and Edit Text 

RichTextBox control hosts a collection of RichTextBoxItem. The following code snippet adds items to a RichTextBox control.

   

<RichTextBox Margin="10,10,0,13" Name="RichTextBox1" HorizontalAlignment="Left"   
             VerticalAlignment="Top" Width="500" Height="300">  
    <FlowDocument>  
        <Paragraph>  
            I am a flow document. Would you like to edit me?  
            <Bold>Go ahead.</Bold>                  
        </Paragraph>  
        
        <Paragraph Foreground="Blue">            
            I am blue I am blue I am blue.    
        </Paragraph>  
    </FlowDocument>          
</RichTextBox> 

The preceding code generates Figure 1 where you can begin editing text right away.

RichTextBox with editable text

Creating and Using RichTectBox Dynamically 

In the previous section, we saw how to create and use a RichTextBox in XAML. WPF provides the RichTextBox class that represents a RichTextBox control. In this section, we will see how to use this class to create and use a RichTextBox control dynamically. 

The code listed in Listing 1 creates a FlowDocument, adds a paragraph to the flow document and sets the Document property of the RichTextBox to FlowDocument.

       


private void CreateAndLoadRichTextBox()  
{  
    // Create a FlowDocument  
    FlowDocument mcFlowDoc = new FlowDocument();  
  
    // Create a paragraph with text  
    Paragraph para = new Paragraph();  
    para.Inlines.Add(new Run("I am a flow document. Would you like to edit me? "));  
    para.Inlines.Add(new Bold(new Run("Go ahead.")));  
  
    // Add the paragraph to blocks of paragraph  
    mcFlowDoc.Blocks.Add(para);  
  
    // Create RichTextBox, set its hegith and width  
    RichTextBox mcRTB = new RichTextBox();  
    mcRTB.Width = 560;  
    mcRTB.Height = 280;  
  
    // Set contents  
    mcRTB.Document = mcFlowDoc;  
  
    // Add RichTextbox to the container  
    ContainerPanel.Children.Add(mcRTB);       
}  

Listing 1

The output of Listing 1 generates Figure 2.

Listing 1 doc

Enable Spelling Check 

RichTextBox control comes with spell check functionality out-of-the-box. By setting theSpellCheck.IsEnabled property to true enables spell checking in a RichTextBox

SpellCheck.IsEnabled="True"  

You can set this in code as follows:

mcRTB.SpellCheck.IsEnabled = true;  

Now if you type some text, the wrong word would be underlined with the Red color. See in Figure 3.

RichTextBox with Spell Check Enabled


Loading a Document in RichTextBox
We can use the RichTextBox.Items.Remove or RichTextBox.Items.RemoveAt methods to delete an item from the collection of items in the RichTextBox. The RemoveAt method takes the index of the item in the collection. 
Now, we modify our application and add a new button called Delete Item. The XAML code for this button looks as in the following:  

private void LoadTextDocument(string fileName)  
{  
    TextRange range;  
    System.IO.FileStream fStream;  
    if (System.IO.File.Exists(fileName))  
    {  
        range = new TextRange(RichTextBox1.Document.ContentStart, RichTextBox1.Document.ContentEnd);  
        fStream = new System.IO.FileStream(fileName, System.IO.FileMode.OpenOrCreate);  
        range.Load(fStream, System.Windows.DataFormats.Text );  
        fStream.Close();  
    }  
}

READ MORE

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. 

   <Viewbox Height="200" HorizontalAlignment="Left" Margin="19,45,0,0"   
         Name="viewbox1" VerticalAlignment="Top" Width="300"  
         Stretch="Fill">  
    <Ellipse Width="100" Height="100" Fill="Red" />      
</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.

 private void CreateViewboxDynamically()  
  {  
    Viewbox dynamicViewbox = new Viewbox();  
    dynamicViewbox.StretchDirection = StretchDirection.Both;  
    dynamicViewbox.Stretch = Stretch.Fill;  
    dynamicViewbox.MaxWidth = 300;  
    dynamicViewbox.MaxHeight = 200;  
  
    Ellipse redCircle = new Ellipse();  
    redCircle.Height = 100;  
    redCircle.Width = 100;  
    redCircle.Fill = new SolidColorBrush(Colors.Red);  
    dynamicViewbox.Child = redCircle;    
    RootLayout.Children.Add(dynamicViewbox);  
}  

Summary

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

READ MORE
...