top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to use XAML RepeatButton in WPF?

+4 votes
712 views

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

posted Mar 1, 2016 by Jdk

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


Related Articles

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

The XAML Tooltip element represents a window tooltip. A ToolTip is a pop-up window that displays some information in a small window. This article shows how to use a ToolTip control in WPF.

Creating a ToolTip

The ToolTip element represents a ToolTip control in XAML

<ToolTip/>  

The IsOpen property indicates whether or not a ToolTip is visible. The HorizontalOffset and VerticalOffsetproperties represent the horizontal and vertical distance between the target control and the pop-up window. The Content property represents the contents of the ToolTip. 

The code snippet in Listing 1 creates a ToolTip control and sets the horizontal offset, vertical offset and content of a ToolTip control. 

   

<ToolTip Content="Hello! I am a ToolTip."   
HorizontalOffset="10" VerticalOffset="20"/> 

                                                            Listing 1

The output looks as in Figure 1. 

                                              Creating a ToolTip
                                       

ToolTip Service

To display a tooltip for a control, the ToolTipService class must be used. The SetToolTip and GetToolTipstatic methods are used to set and get the tooltip of a control. 

The following code snippet creates a ToolTipService.ToolTip for a control.

    

<ToolTipService.ToolTip >   
    <ToolTip Content="Hello! I am a ToolTip."   
    HorizontalOffset="10" VerticalOffset="20"/>  
</ToolTipService.ToolTip>   

                           

 <Button Content="Mouse over me" Width="150" Height="30"  
        Canvas.Top="10" Canvas.Left="10">  
    <ToolTipService.ToolTip >   
        <ToolTip Content="Hello! I am a ToolTip."   
        HorizontalOffset="10" VerticalOffset="20"/>  
    </ToolTipService.ToolTip>  
</Button>                                            


Then if you run the application and hover the mouse over the button control, the output looks as in Figure 2.

                                    ToolTip Service
                                                       

Creating a Fancy Tooltip

The ToolTip content can be any control and multiple controls. The code snippet in Listing 4 creates aToolTip with an image and text in it. 

          <!-- Create a button -->  
<Button Content="Mouse over me" Width="150" Height="30"   
        Canvas.Top="50" Canvas.Left="20">  
    <!-- Create a tooltip by using the ToolTipService -->  
    <ToolTipService.ToolTip >  
        <ToolTip HorizontalOffset="0" VerticalOffset="0">  
            <!-- Add a StackPanel to the tooltip content -->  
            <StackPanel Width="250" Height="150">  
                <!-- Add an image -->  
                <StackPanel.Background>  
                    <ImageBrush ImageSource="Garden.jpg"  
                                Opacity="0.4"/>  
                </StackPanel.Background>  
                <!-- Add a text block -->  
                <TextBlock >  
                    <Run Text="This is a tooltip with an image and text"  
                        FontFamily="Georgia" FontSize="14" Foreground="Blue"/>  
                </TextBlock>  
            </StackPanel>  
        </ToolTip>  
    </ToolTipService.ToolTip>  
</Button>                                       


The new tooltip looks as :

                  Creating a Fancy Tooltip
                                     

 

READ MORE

The XAML Toolbar element represents a window toolbar. A ToolBar control is a group of controls that are typically related in functionality. A typical ToolBar is a toolbar in Microsoft Word and Visual Studio where you see File Open, Save and Print buttons. 

This article discusses basic components of ToolBar controls in WPF and how to use them in your applications. 

Creating a Toolbar

The ToolBar element in XAML represents a WPF ToolBar control. 

<ToolBar />  
The code snippet in Listing 1 creates a ToolBar control and sets its width and height properties. You may place any control on a ToolBar but typically buttons are used. A ToolBar sits on a ToolBarTray. The code snippet in Listing 1 adds three buttons to the ToolBar and places a ToolBar on a ToolBarTray.
<ToolBarTray Background="DarkGray" Height="30" VerticalAlignment="Top">  
  
<ToolBar Name="MyToolbar" Width="200" Height="30" >  
    <Button Background="LightSkyBlue" Content="Open" />  
    <Button Background="LightSkyBlue" Content="Close" />  
    <Button Background="LightSkyBlue" Content="Exit" />  
</ToolBar>  
  
</ToolBarTray>  
                                                      Listing 1


The output looks as in Figure 1. 

         window
                                                      Figure 1

Adding ToolBar Button Click Event Handlers

The best part of WPF is that these buttons are WPF Button controls so you have a choice to use them on any other button. You may format them the way you like. You may add a click event handler to them and so on. 

The code snippet in Listing 2 adds click event handlers to all three ToolBar buttons. 
<ToolBar Name="MyToolbar" Width="200" Height="30"  >  
    <Button Background="LightSkyBlue" Content="Open" Name="OpenButton" Click="OpenButton_Click"  />  
    <Button Background="LightSkyBlue" Content="Close" Name="CloseButton" Click="CloseButton_Click"  />  
    <Button Background="LightSkyBlue" Content="Exit" Name="ExitButton" Click="ExitButton_Click"   />  
 </ToolBar>  
                                                      Listing 2

On these button click event handlers, you would want to write the code you want to execute when these buttons are clicked. For example, I show a message when these buttons are clicked. The code for these button click event handlers is as in Listing 3.
private void OpenButton_Click(object sender, RoutedEventArgs e)  
{  
    MessageBox.Show("Open button is clicked.");  
}  
  
private void CloseButton_Click(object sender, RoutedEventArgs e)  
{  
    MessageBox.Show("Close button is clicked.");  
}  
  
private void ExitButton_Click(object sender, RoutedEventArgs e)  
{  
    MessageBox.Show("Exit button is clicked.");  
}  
                                                      Listing 3

If you click on the Open button, you will see Figure 2 as output. 

                                    button
                                                      Figure 2

Adding Images to ToolBar Buttons 

Usually ToolBars look nicer than just displaying text. In most cases, they have icons. Displaying an Icon image on a button is simply placing an Image control as the content of a Button. The code snippet in Listing 4 changes the Button contents from text to images. 
<ToolBarTray Background="DarkGray" Height="30" VerticalAlignment="Top">  
    <ToolBar Name="MyToolbar" Width="200" Height="30" Background="LightCoral" >  
        <Button Name="OpenButton" Click="OpenButton_Click">  
            <Image Source="Images\camera.png" />  
         </Button>  
        <Button Name="CloseButton" Click="CloseButton_Click">  
            <Image Source="Images\ctv.png" />  
        </Button>  
        <Button Name="ExitButton" Click="ExitButton_Click" >  
            <Image Source="Images\find.png" />  
        </Button>  
    </ToolBar>  
</ToolBarTray>  
                                                      Listing 4

The new ToolBar looks as in Figure 3.

                    ToolBar
                                                      Figure 3

Adding Separators to a ToolBar

You may use a Separator control to give your ToolBar buttons a more prominent look. The code snippet in Listing 4 adds a few extra buttons and a few separators to a ToolBar.
<ToolBarTray Background="DarkGray" Height="30" VerticalAlignment="Top">  
    <ToolBar Name="MyToolbar" Width="180" Height="30" Background="LightCoral" >  
        <Separator />  
        <Button Name="OpenButton" Click="OpenButton_Click">  
            <Image Source="Images\camera.png" />  
         </Button>  
        <Button Name="CloseButton" Click="CloseButton_Click">  
            <Image Source="Images\ctv.png" />  
        </Button>  
        <Button Name="ExitButton" Click="ExitButton_Click" >  
            <Image Source="Images\find.png" />  
        </Button>  
        <Separator Background="Yellow" />  
        <Button >  
            <Image Source="Images\award.png" />  
        </Button>  
        <Button >  
            <Image Source="Images\cuser.png" />  
        </Button>  
        <Button >  
            <Image Source="Images\next.png" />  
        </Button>  
        <Button >  
            <Image Source="Images\code.png" />  
        </Button>  
        <Separator />  
    </ToolBar>  
</ToolBarTray>  
                                                      Listing 5

The ToolBar with separators looks as in Figure 4. Also, if you notice there is a drop array that is available when buttons do not fit in a ToolBar. If you click on that, you will see the rest of the buttons.

   
         fit in a ToolBar
                                                      Figure 4

Summary

In this article, I discussed how to use a ToolBar control in WPF and C#.

READ MORE

The XAML TextBlock element represents a text block. The TextBlock control provides a lightweight control for displaying small amounts of flow content. This article shows how to use a TextBlock control in WPF.

Creating a TextBlock

The TextBlock element represents a WPF TextBlock control in XAML. 

  1. <TextBlock/>  

The Width and Height attributes of the TextBlock element represent the width and the height of aTextBlock. The Text property of the TextBlock element represents the content of a TextBlock. The Name attribute represents the name of the control that is a unique identifier of a control. The Foreground property sets the foreground color of contents. This control does not have a Background property. 

The code snippet in Listing 1 creates a TextBlock control and sets the name, height, width, foreground and content of a TextBlock control. Unlike a TextBox control, the TextBlock does not have a default border around it.

<TextBlock Name="TextBlock1" Height="30" Width="200"   

    Text="Hello! I am a TextBlock." Foreground="Red">  

</TextBlock>  

Listing 1

The output looks as in Figure 1

                                          output
                                                      Figure 1

As you can see from Figure 1, by default the TextBlock is placed in the center of the page. We can place aTextBlock control where we want using the MarginVerticalAlignment and HorizontalAlignment attributes that sets the margin, vertical alignment and horizontal alignment of a control. 

The code snippet in Listing 2 sets the position of the TextBlock control in the left top corner of the page. 

<TextBlock Name="TextBlock1" Height="30" Width="200"   
        Text="Hello! I am a TextBlock."   
        Margin="10,10,0,0" VerticalAlignment="Top"   
        HorizontalAlignment="Left">              
</TextBlock>  ​

                                                      Listing 2

Creating a TextBlock Dynamically

The code listed in Listing 3 creates a TextBlock control programmatically. First, it creates a TextBlockobject and sets its width, height, contents and foreground and later the TextBlock is added to theLayoutRoot

private void CreateATextBlock()  
{  
    TextBlock txtBlock = new TextBlock();  
    txtBlock.Height = 50;  
    txtBlock.Width = 200;  
    txtBlock.Text = "Text Box content";  
    txtBlock.Foreground = new SolidColorBrush(Colors.Red);  
  
    LayoutRoot.Children.Add(txtBlock);  
} ​

                                                      Listing 3

Setting Fonts of TextBlock Contents

The FontSizeFontFamilyFontWeightFontStyle and FontStretch properties are used to set the font size, family, weight, style and stretch to the text of a TextBlock. The code snippet in Listing 4 sets the font properties of a TextBlock

  1. FontSize="14" FontFamily="Verdana" FontWeight="Bold"  

                                                      Listing 4

The new output looks as in Figure 4.

                                    hello

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
...