Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Windows Presentation Foundation Development Cookbook
Windows Presentation Foundation Development Cookbook

Windows Presentation Foundation Development Cookbook: 100 recipes to build rich desktop client applications on Windows

eBook
R$80 R$294.99
Paperback
R$367.99
Subscription
Free Trial
Renews at R$50p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

Windows Presentation Foundation Development Cookbook

Using WPF Standard Controls

In this chapter, we will cover the following recipes:

  • Using the TextBlock control to add plain text
  • Using Label to add other controls in text
  • Providing a user option to input text
  • Adding images in your application UI
  • Working with ready-to-use 2D shapes
  • Adding tooltips to show additional information
  • Adding a standard menu to the WPF application
  • Providing extra functionalities using the context menu
  • Adding user options with radio buttons and checkboxes
  • Working with the progress bar control
  • Using the Slider control to pick a numeric value
  • Using the calendar control in your application
  • Listing items in a ListBox control
  • Providing options to select from a ComboBox
  • Adding a status bar to your window
  • Adding a toolbar panel to perform quick tasks

Introduction

Every UI Framework must provide the standard controls to design the application UI and Windows Presentation Foundation (WPF) is one of them. WPF provides a set of standard controls and UI elements such as TextBlock, TextBox, Button, Image, various shapes, ProgressBar, Slider, various menus, Toolbar, ListBox, ComboBox, DataGrid, and more.

As you can see from the following diagram, UI controls can be of two types—ItemsControl and ContentControl, which inherit from Control class. All the panels available in WPF share the same base class Panel. The Control and Panel class have the base FrameworkElement, which again inherits from the UIElement. It has the base class as the DependencyObject and the superbase as the Object:

Every control has some common set of properties exposed. This includes FontFamily, FontSize, FontStyle, Foreground, Background, BorderBrush, BorderThickness, and more. Every framework element exposes additional properties such as Width, MaxWidth, MinWidth...

Using the TextBlock control to add plain text

The TextBlock control in WPF is a lightweight UI element, which is used to display text content to the screen. Almost everywhere, you will use this element in your application UI to display plain text in a single line or a multiline format. To add simple plain text, you can either write <TextBlock Text="Text message" /> or <TextBlock>Text message</TextBlock> in your XAML page.

In this recipe, we will explore more about this UI element.

Getting ready

To get started, open your Visual Studio IDE, and create a new WPF project called CH02.TextBlockDemo.

How to do it...

Now open the MainWindow.xaml, and follow these steps to add TextBlock control with various formatting options:

  1. First, change the pre-existing Grid panel to a StackPanel.
  2. Now add the following two TextBlock controls to it, which will have plain text in them:
<TextBlock Text="1. This is a TextBlock control, with 'Text'   
property" Margin="10 5" /> <TextBlock Margin="10 5"> 2. This is a TextBlock control, having text as Content </TextBlock>
  1. Add the following XAML to have a few more TextBlock controls, with some basic text formatting applied to them:
<TextBlock Text="3. This is a TextBlock control, having text    
formatting" FontWeight="Bold" FontStyle="Italic" TextDecorations="Underline" Foreground="Red" Margin="10 5" /> <TextBlock Text="4. TextBlock with...

How it works...

For the first two TextBlock controls, the UI will have a plain text on it. The third TextBlock control will have Bold, Italic, and Underline applied to it, by specifying the FontWeight, FontStyle, and TextDecoration properties of the control. Also, the foreground color of it has been set to red, by specifying the Foreground property.

You can also set a different font to your TextBlock control. Use the FontFamily property to set it. As you can see, the fourth TextBlock control has a Lucida Handwriting font applied to it.

When you have a long text, which is not viewable in a single line, you can either wrap it to multiline or trim it, based on the available space. TextWrapping="Wrap", in the fifth TextBlock spans it to multiline. Try making the window bigger or smaller, and you will see that the TextBlock automatically adjusts itself to match the available space, whereas, the text of the sixth TextBlock control trims with the TextTrimming property set to character...

There's more...

The TextBlock control also supports inline formatting. Just like HTML tags, you can surround a text content with Bold, Italic, and Underline tags to format it, as shown in the following XAML code:

<TextBlock Margin="10, 5"> 
    7. TextBlock with <Bold>Bold</Bold>, <Italic>Italics</Italic>, <Underline>Underlined</Underline> text 
</TextBlock> 

You can also add a line break to a text content, like this:

<TextBlock Margin="10, 5"> 
    8. TextBlock with LineBreak<LineBreak/> in between the text 
</TextBlock> 

The following XAML code demonstrates how to add a hyperlink element to a TextBlock control that matches the style of your Windows theme:

<TextBlock Margin="10, 5"> 
    9. TextBlock with a <Hyperlink NavigateUri="http://www.kunal-chowdhury.com">Hyperlink</Hyperlink> text in it 
</TextBlock> 

The NavigateUri property is used to define...

Using Label to add other controls in text

The Label control is another way of representing text in WPF application. It looks like what TextBlock control offers, but instead of having only text support, it can also host any kind of other controls. It exposes the Content property to host text and other controls.

In this recipe, we will explore how to use the Label control in a WPF.

Getting ready

To get started with this control, open Visual Studio to create an application based on the WPF project template and call it CH02.LabelDemo.

How to do it...

Once the project gets created, follow these simple steps to add text in your application UI, using the Label control:

  1. Open the MainWindow.xaml file to change the application UI.
  2. Replace the existing Grid panel with the following XAML code:
<StackPanel Margin="10 10 10 20"> 
    <Label Content="1. This is a Label control" /> 
    <Label Content="2. A Label control with text formatting" 
            FontWeight="Bold" Foreground="Red" 
            FontStyle="Italic"/> 
    <Label> 
        <StackPanel Orientation="Horizontal"> 
            <TextBlock Text="3. A Rectangle" /> 
            <Rectangle Width="20" Height="20" Fill="Red" 
Margin="10 0" /> <TextBlock Text="inside a Label control" /> </StackPanel> </Label> </StackPanel>
  1. Now build...

How it works...

The first control added in the StackPanel is a very basic label, which has plain text as its Content property. The second Label control also contains plain text, but has various formatting (such as, FontWeight, Foreground, and FontStyle) applied to it to give it a bold, italic, and red color look to its style.

As the Label control derives from System.Windows.Controls.ContentControl, it also supports adding other controls to its content. The third label added to the UI is a little different than the previous two examples. It not only contains text, but also other controls, such as StackPanel, TextBlock, and a Rectangle, owing to its Content property.

In the preceding example, for the third label, the TextBlock control is used to hold the actual text content, and StackPanel is used as a panel control to hold both the TextBlock and the Rectangle.

A point to remember is that Label is heavier than a TextBlock. So, when you need to render a plain text on the UI, prefer TextBlock...

There's more...

In Windows and other operating systems, it's a widespread practice to access the controls in a window by holding the Alt key and then pressing a character defined as its access key. For example, to open the File menu of any Windows application, we use Alt + F. Here, the character F is the access key, which gets invoked when we press Alt.

Let's learn how to add an access key to labels in the WPF application, using the Label control. Create a new project called CH02.LabelAccessKeyDemo, open the MainWindow.xaml page, and replace the default Grid by a StackPanel. Now add two labels and two textboxes inside the StackPanel, as follows:

<StackPanel Margin="10 10 10 20"> 
    <Label Content="Enter _Username:" 
            Target="{Binding ElementName=txbUsername}" /> 
    <TextBox x:Name="txbUsername" Margin="6 0" /> 
 
    <Label Content="Enter _Password:" 
            Target=&quot...

Providing a user option to input text

The TextBox control in WPF is used to allow the user to input plain text in a single line or multiline format. A single-line textbox is the commonly used control for form inputs; whereas the multiline textbox is used like an editor.

Getting ready

Open your Visual Studio IDE, and create a new project named CH02.TextBoxDemo, based on the WPF application template.

How to do it...

Once the project gets created, follow the mentioned steps to play with some of the TextBox properties:

  1. Open the MainWindow.xaml page, and replace the default Grid with a StackPanel so that we can add the controls in a stacked fashion.
  2. Now add five TextBox controls inside the StackPanel, and set various properties, as follows:
<StackPanel Margin="10 10 10 20">
<TextBox Height="30" Margin="10 5"
Text="Hello"/>
<TextBox Text="Hello WPF!"
FontSize="18" Foreground="Blue"
FontWeight="Bold"
Height="30" Margin="10 5"/>
<TextBox Text="This is a 'ReadOnly' TextBox control"
IsReadOnly="True" Height="30" Margin="10 5"/>
<TextBox Text="This is a 'Disabled' TextBox control"
...

How it works...

The first TextBox control, which we added to the StackPanel, is the simplest one, and when it is rendered in the UI, it contains empty text. The user can enter any plain text here. You can also specify text from code, by using the Text property, as shown in the second control.

You can also define a range of styles for the text of the TextBox control. As shown in the second control, we specified FontSize, Foreground, FontWeight. You can specify other properties too, as part of any control.

The third one is a ReadOnly textbox, which you can define by setting the IsReadOnly property value to True. When you want to disable a TextBox, set its IsEnabled property to False, as shown in the fourth example.

The fifth example demonstrates how easy it is to define a multiline textbox. Just set its AcceptsReturn property to True and TextWrapping to Wrap. The control will behave like a multiline text editor.

There's more...

When you are using TextBox as a multiline text-input control, don't forget to set its VerticalScrollBarVisibility. This will allow your user to scroll the text content. As shown in the last example, set it to Auto to make it enabled on demand, based on its content.

Windows Clipboard support

The TextBox control automatically supports the Windows Clipboard. Right-click on it to see the context menu pop up in the screen with common clipboard functions, such as Select all, Cut, Copy, and Paste. Along with these functions, it also supports the common keyboard shortcuts for clipboard operations, undo/redo, by default.

Adding spellcheck support

The attached SpellCheck.IsEnabled property allows you to add spellcheck support to the TextBox control. Set it to True to enable it. Let's add a multiline textbox in the UI with this feature enabled:

<TextBox TextWrapping="Wrap" AcceptsReturn="True" 
         Height="60" VerticalScrollBarVisibility="Auto" 
         SpellCheck.IsEnabled="True" 
         Margin="10 5" /> 

Now run the application to have a window with a multiline text-input field in the UI. Enter some text with some spelling mistakes. You will see that the wrongly spelled words get highlighted with red underline. Right-click on it to see a context menu, which suggests words from the dictionary.

As shown in the following screenshot, select the one that is best suited in this context:

Adding images to your application UI

Images are used to create a UI that looks good, with a background, icons, and thumbnails, and they convey more information to the user. In WPF, the Image element is used to display images. Let's take a look at this.

Getting ready

To get started with images in WPF, launch your Visual Studio IDE and create a WPF project called CH02.ImageDemo, and add an image called demoImage.jpg.

How to do it...

Let's follow these steps to add images in the MainWindow.xaml page:

  1. Open the MainWindow.xaml page, and replace the existing Grid with a StackPanel. Set its Orientation property to Horizontal so that the items added to this panel stack themselves horizontally.
  2. Add four images to the StackPanel, and set their Source property to demoImage.jpg, which is available within the project directory.

  1. Set the width and the height of each image to 100.
  2. For the first image, set its Stretch property to None.
  3. For the second image, set its Stretch property to Fill.
  4. For the third and fourth images, set their Stretch property to Uniform and UniformToFill, respectively.
  5. Here's the complete XAML code, to which you can refer:
<StackPanel Orientation="Horizontal"> 
    <Image Source="demoImage.jpg" 
           Stretch="None" 
           Width="100" Height="100"  
           Margin="10 10 5 10" /> 
    &lt...

How it works...

In XAML, the Source property of the Image control is the path of the image file that you want to display. When you access the same from code, it's a BitmapImage.

The Stretch property of an image describes how it should be stretched to fill the destination. For the first image, that we set as Stretch= "None", it preserves the original size of the image. When you set it as Fill, for the second image in the example, the content is resized to fill the destination dimensions without preserving its aspect ratio.

For the third and fourth image, setting it to Uniform and UniformToFill, respectively, set its content resized to fit in the destination dimensions while preserving its native aspect ratio. But for the fourth case, if the aspect ratio of the destination image differs from the source, the source content is clipped to fit in the destination dimensions.

The default value of the image Stretch property is Uniform. That means, when you add an image to the UI...

There's more...

You can also set an image in XAML by creating a BitmapImage instance and assigning it to its Source property. The BitmapImage instance exposes the UriSource property to set the image path. Here's an example of how to set the image source in XAML, using the BitmapImage element:

<Image> 
    <Image.Source> 
        <BitmapImage UriSource="demoImage.jpg" /> 
    </Image.Source> 
</Image> 

You can also rotate an image by setting the Rotation property of BitmapImage. It contains four values Rotate0, Rotate90, Rotate180, and Rotate270. Here's an example to demonstrate how to rotate an image by 180 degrees:

<Image> 
    <Image.Source> 
        <BitmapImage UriSource="demoImage.jpg" 
                     Rotation="Rotate180"/> 
    </Image.Source> 
</Image> 

Additionally, you can also use the StretchDirection property of an Image control. The value indicates how the image is...

Working with ready-to-use 2D shapes

In WPF, a Shape is an UIElement that enables you to draw a 2D shape in your application. There are a couple of ready-to-use shapes already provided by WPF, and they are as follows:

  • Rectangle
  • Ellipse
  • Line
  • Polyline
  • Polygon
  • Path

All of these UIElements expose some common properties to draw the shape. The Stroke and StrokeThickness properties describe the color and the thickness to draw the shape's outline. The Fill property describes the color used to decorate the interior of the shape.

In this recipe, we will learn how to create various shapes.

Getting ready

Let's begin with creating a new project. Open your Visual Studio, and create a WPF project called CH02.ShapesDemo. As we will be creating multiple shapes, we will be using the UniformGrid panel to host the shapes in this demonstration. You can learn more about this panel in the next chapter.

How to do it...

Follow these steps to create various shapes in your application:

  1. Open your MainWindow.xaml file, and replace the existing Grid panel with UniformGrid. Set its maximum columns count to 3, by setting its Column property.
  2. Let's add our first shape, a Rectangle. Add the following XAML code inside the UniformGrid:
<Rectangle Width="200" Height="100" 
           Stroke="DarkBlue" StrokeThickness="5" 
           Fill="SkyBlue" Margin="10 5" /> 
  1. Now let's add an Ellipse, which you can change to a circle by setting the same value to its Height and Width properties. Add the following code to create the ellipse:
<Ellipse Width="200" Height="100" 
         Stroke="DarkBlue" StrokeThickness="5" 
         Fill="SkyBlue" Margin="10 5" /> 
  1. To add a Line in the panel, add the following XAML:
<Line X1="10" Y1="80" X2=...

How it works...

A rectangular shape is being drawn by setting the Height and Width properties of the Rectangle class, along with the stroke color and the thickness of it. To create a square, you can use this shape by setting its dimension properly.

In the second example, a circular shape has been drawn using the Ellipse control. It uses the same property sets to create the shape. To make it a complete circle, set its Height and Width to the same value.

If you want to draw a straight line in the UI, use the Line class. It exposes four properties to draw the line. Set the X1 and Y1 properties to mark the starting point; set X2 and Y2 properties to mark the ending point of the line. In the preceding example, a line has been drawn from the (10,80) coordinate point to the (190,20) coordinate point.

In the fourth example, we have seen how to create a series of connected straight lines using the Polyline shape control. You need to set the (X, Y) coordinate points of the lines in its Points...

There's more...

The PathGeometry objects are used to draw lines, curves, arcs, and complex shapes. WPF provides two classes to describe the geometric paths using the mini language Path Markup Syntax.

You can learn more about it here:
http://bit.ly/path-markup-syntax

If you want to draw simple shapes, you can use the EllipseGeometry, LineGeometry, and RectangleGeometry objects. Composite geometries are created by GeometryGroup and to create combine geometries, use the CombineGeometry.

Let's take the following example to demonstrate a complex path geometry using a PathSegmentCollection of three segments:

<Path Stroke="DarkBlue" StrokeThickness="5"> 
    <Path.Data> 
        <PathGeometry> 
            <PathGeometry.Figures> 
                <PathFigureCollection> 
                    <PathFigure StartPoint="10,100"> 
                        <PathFigure.Segments> 
                            <PathSegmentCollection...

Adding tooltips to show additional information

Tooltips are used to show additional information about a specific control or a link when hovering your mouse over it. The FrameworkElement class exposes a property named Tooltip, which you can find on all the controls available in WPF.

In this recipe, we will learn how to work with the tooltips in WPF. We will also cover how to design a tooltip using other controls.

Getting ready

Open your Visual Studio IDE and create a new WPF application project called CH02.TooltipDemo.

How to do it...

Open the MainWindow.xaml page, and then follow these steps to add simple tooltips to the UI:

  1. First, replace the default Grid with a StackPanel, and set its Orientation property to Horizontal to have some horizontally stacked items.
  2. Add three buttons to the StackPanel, and set their ToolTip property. To add a show duration of the tooltip, set its ToolTipService.ShowDuration attached property to a value in milliseconds. You can use the following XAML as a reference:
<StackPanel Orientation="Horizontal" 
            HorizontalAlignment="Center" 
            Margin="20"> 
    <Button Content="New" Width="60" Height="30"  
            ToolTip="Create a New file" 
            Margin="4" /> 
    <Button Content="Open" Width="60" Height="30"  
            ToolTip="Open a file" 
            ToolTipService.ShowDuration="2000" 
      ...

How it works...

The ToolTip property, when set in any WPF control, gets visible when you hover over the control. Apart from this, the ToolTipService class has a bunch of attached properties to help you set various behaviors of the tooltip.

Like the second example, as shown earlier, if you hover over the Open button, the Tooltip property will be visible on screen for 2 seconds. This is because we set the ShowDuration property of the ToolTipService to 2000 milliseconds (2 seconds).

You can also use the ToolTipService.ShowOnDisabled property to show or hide a Tooltip on an element that is disabled. The HasDropShadow property of the class ensures whether the Tooltip will have a shadow on it.

There's more...

As the ToolTip property is of object type, you can assign anything to it, including various UI controls. Hence, it helps you to customize the UI of the tooltip with a much richer experience.

Let's modify the Tooltip property of the third button in the preceding example. Place a few TextBlock and Border controls in a StackPanel to design the UI, as shared in the following XAML code snippet:

<Button Content="Save" Width="60" Height="30"  
    Margin="4"> 
    <Button.ToolTip> 
        <StackPanel> 
            <TextBlock FontWeight="Bold" 
                       Text="Save File" /> 
            <TextBlock Text="Clicking on this button, 
saves the file to disk" FontSize="10" /> <Border BorderBrush="Silver" BorderThickness="0,1,0,0" ...

Adding a standard menu to the WPF application

One of the most common parts of WPF applications is the menu, as it gives various options within a very little space. WPF comes with a control named Menu, to hold items named MenuItem.

Let's learn more about this menu control and how to add it to Windows applications.

Getting ready

Open your Visual Studio, and create a new WPF project called CH02.MenuDemo.

How to do it...

Follow these steps to add menus to your WPF application:

  1. Open the MainWindow.xaml page, and replace the default Grid with a DockPanel. We will discuss more about this panel in the next chapter.
  2. Now add the Menu control inside the DockPanel. This will create the base to hold all the menu items.
  3. You can then add root-level menu items and sub-menu items in a hierarchical fashion, as shown in the following code snippet:
<DockPanel> 
    <Menu> 
        <MenuItem Header="File"> 
            <MenuItem Header="New" /> 
            <MenuItem Header="Open" /> 
            <MenuItem Header="Save" /> 
            <Separator /> 
            <MenuItem Header="Exit" /> 
        </MenuItem> 
        <MenuItem Header="Edit"> 
            <MenuItem Header="Undo" /> 
            <MenuItem Header="Redo" /> 
        </MenuItem> 
 ...

How it works...

When you add the first menu item under the <Menu> tag, it creates the root-level menu item; for example, File menu, Edit menu. Each root menu item can contain one or more hierarchical sub-menu items. In the preceding example, the File menu contains four sub-menu items.

The header property of the MenuItem is used to add the label of each item. When you want to add a separator, you can do so by adding the <Separator /> tag, as shown in the preceding example. A separator does not need any Header content.

There's more...

You can further customize a menu entry to have an icon, a check-mark, a shortcut key, or a keyboard access specifier. Let's discuss each of them.

Adding an access key to menus

It's a general practice to access application menus by holding the Alt key and then pressing the character defined as its access key. For example, to open the File menu of any Windows application, we use Alt + F, and to access the File | New menu, we use Alt + F, N. Here, the character F and N are used as access keys that are invoked when we press Alt.

In the WPF application, you need to specify _ (underscore) before the character you want to highlight as the access key. For example, adding _ before the F in File menu header content activates the said menu when Alt + F is pressed:

<MenuItem Header="_File"> 
      <MenuItem Header="_New" /> 
      <MenuItem Header="_Open" /> 
</MenuItem> 

The frequently used practice is to use the first character that's not already used as an access key of another control. But, on a need basis, you can specify any character part of the label content.

Adding icons to menus

You can add icons to menus to give a better look to the application's menu items. The MenuItem element contains a property named Icon to add an image icon or a Unicode character as an icon to it.

Let's add a Unicode character to add an icon for the Open and Save menu items:

Run the application now to see the icons added to the said menus, as shown in the following screenshot:

Adding checkable menu items

You can add checkable menu items too. The WPF menu item exposes two properties to handle this. The IsCheckable property tells the menu item that it can handle check/uncheck options. When IsCheckable is set to True, it sets to the check/uncheck icon on an alternate click of that menu item.

You can also programmatically check/uncheck a menu item. Set its IsChecked property to True or False. Make sure to set IsCheckable="True". Let's add the following menu item, under the Edit menu:

<MenuItem Header="Save _settings on exit" 
          IsCheckable="True" IsChecked="True" /> 

Adding click-event handlers to menus

Menus are not just to add to the application; you need to perform some actions on the menu with a click by adding the Click event handler, as shown in the following code snippet:

<MenuItem Header="E_xit" Click="OnExitMenuClicked" /> 

In the code behind, implement the handler, as shown in the following code:

private void OnExitMenuClicked(object sender, RoutedEventArgs e) 
{ 
    MessageBox.Show("'Exit' menu item clicked!"); 
    Environment.Exit(0); 
} 

This will first show a message box and then exit the application when the user clicks on the Exit menu item.

Providing extra functionalities using the context menu

The context menu provides a vital role in any Windows applications offering additional functionalities to the user, within that context. This is often done relevant to a single control or a window.

When you right-click on a control or a window, you can provide a popup context menu to the user, to perform single-click actions. WPF provides a ContextMenu property to all framework elements to hold a ContextMenu, having hierarchical MenuItems.

Consider this recipe to learn more about adding a context menu in your WPF application.

Getting ready

Create a new project named CH02.ContextMenuDemo, using the WPF application project template of Visual Studio.

How to do it...

Follow these steps to add a context menu to a TextBlock control. The same steps can be followed to add a context menu to any of the controls inheriting FrameworkElement:

  1. Open the MainWindow.xaml file to modify the application UI.
  2. Replace the entire Grid block with the following XAML code:
<Grid> 
    <TextBlock Text="Right-click on me to open Context Menu!" 
        Margin="10"> 
        <TextBlock.ContextMenu> 
            <ContextMenu> 
                <MenuItem Header="Menu item 1" /> 
                <MenuItem Header="Menu item 2" 
                    InputGestureText="Ctrl + R, Ctrl + G"/> 
                <Separator /> 
                <MenuItem Header="Menu item 3" 
                          IsCheckable="True"  
                          IsChecked="True" /> 
            </ContextMenu> 
        </TextBlock.ContextMenu> 
  ...

How it works...

As you see from the preceding example, each FrameworkElement exposes a property named ContextMenu, which can hold a ContextMenu item. Just like the menu, as we learnt in the previous recipe, the context menu can also hold multiple items as MenuItem, and each menu item can again hold one or more menu items to make the context menu hierarchical.

Labels of menu items are assigned by setting its Header property. You can also set icons for each menu item, by assigning an image or a Unicode character to its Icon property. If you have binded a command to the menu, you can assign the shortcut key text as InputGestureText property.

Additionally, you can create checkable context menu items. As shown in the Menu item 3, you can set the IsCheckable property to True, to make the menu checkable. Then you can use the IsCheck property to show/hide the check mark on it.

To add a separator between a group of context menu items, you can use the <Separator /> tag, as shown in the preceding...

Adding user options with radio buttons and checkboxes

Radio buttons and check boxes have a vital role in Windows Application Development. They are mostly used to provide the user an option to select from a group of items. Radio buttons allow you to select one from a group of options, whereas a checkbox allows you to toggle an option.

In this recipe, we will learn how to use RadioButton and CheckBox controls in the WPF application.

Getting ready

To get started, open your Visual Studio IDE, and create a new project named CH02.OptionSelectorsDemo. Make sure you select the WPF application project template.

How to do it...

Open the MainWindow.xaml page, and follow these steps to add a set of radio buttons and checkbox controls to it:

  1. First, replace the default Grid panel with a StackPanel to hold items stacked vertically.
  2. Now add the following StackPanel with a set of radio buttons with a GroupName="rdoGroup1":
<StackPanel Orientation="Horizontal"> 
    <RadioButton GroupName="rdoGroup1" 
                 Content="Radio 1" 
                 IsChecked="True" 
                 Margin="4" /> 
    <RadioButton GroupName="rdoGroup1" 
                 Content="Radio 2" 
                 Margin="4" /> 
    <RadioButton GroupName="rdoGroup1" 
                 Content="Radio 3" 
                 Margin="4" /> 
</StackPanel>
  1. Add another set of radios, with the GroupName="rdoGroup2", in a horizontally placed StackPanel, and add it to the...

How it works...

The first set of radio button controls are placed in a group with the same name rdoGroup1. When a group name is set to a set of radio buttons, the selection follows that. The first radio button in that group is by default selected, by setting its IsChecked property to True. If you select any other radio button within that group, the previous selection resets to unchecked status.

The same is true for the second group too, but selection of one group does not affect the other group. So, when you check one radio button from the first group, it will not uncheck the radio buttons from the other group.

This is not the same for CheckBox controls. Checkbox controls allow you to have many checked items. When you select a checkbox, it can just toggle from one state to another.

Both the radio button and checkbox control expose the IsChecked property to return a Boolean value to tell whether the control is checked or unchecked.

There's more...

To disable the radio button or the checkbox control, set its IsEnabled property to False. Both the controls expose two events—Checked and Unchecked. When you register the events, the Checked event of the control will trigger when you check that. Similarly, the Unchecked event will trigger when you uncheck that.

Working with the progress bar control

When you perform a lengthy task in the background, you probably would like to add a progress indicator in your application UI to give a visual indication that some work is in progress. WPF provides us with a control name, ProgressBar, to show a percentage value of the work between 0% to 100%, in general.

In this recipe, we will learn about the progress bar control and its various properties.

Getting ready

Let's open the Visual Studio and create a new WPF application project. Name it CH02.ProgressBarDemo.

How to do it...

Once the project gets created, follow these steps to add a progress indicator to the application's UI:

  1. Open the MainWindow.xaml, and replace the existing Grid panel with a StackPanel, so that, we can add our controls stacked vertically.
  2. As shown in the following code snippet, add three ProgressBar controls in the StackPanel:
<StackPanel Margin="10"> 
    <TextBlock Text="Progress Indicator set at: 20%" /> 
    <ProgressBar Height="30" 
                    Margin="0 4" 
                    Minimum="0" 
                    Maximum="100" 
                    Value="20" /> 
         
    <TextBlock Text="Progress Indicator set at: 70%" /> 
    <ProgressBar Height="30" 
                    Margin="0 4" 
                    Minimum="0" 
                    Maximum="100" 
                    Value="70" /> 
    ...

How it works...

The value of the first progress indicator is set to 20, whereas the second progress indicator is set to 70. This denotes that the 20% and 70% job is done respectively. As and when you progress with the task, you can just increment the value to have the visual indication of the progress in the UI, with the ProgressBar control.

For the third ProgressBar control, in the preceding example, it's a bit different. When you are unsure about the total job to be done, you can set its IsIndeterminate property to True, as shown in the preceding screenshot. When your job is done, you can stop the indeterminate state and set its Value to 100.

Using the Slider control to pick a numeric value

The Slider control is used to pick a numeric value by dragging a thumb button along a horizontal or vertical line. This is often used to provide a visualization of a playing video and as a volume indicator.

WPF provides us a control named Slider to quickly implement this in your application UI, and, with a lot of properties for various configurations. Let's learn more about it, in this recipe.

Getting ready

First, create a project named CH02.SliderDemo, based on the WPF application template.

How to do it...

Integration of the slider in WPF is very easy. Just place <Slider /> in your XAML page, and it will start working. But to customize it further, let's follow these steps:

  1. Open the MainWindow.xaml page, and replace the default Grid with a StackPanel.
  2. Now add a Slider and a TextBlock control inside the StackPanel, as shown in the following XAML snippet:
<StackPanel Margin="10"> 
    <Slider x:Name="slider" 
            Minimum="0" Maximum="100"                 
            Value="25" 
            SmallChange="1" 
            LargeChange="5" /> 
    <TextBlock Margin="4"> 
        <Run Text="Current slider value: " /> 
        <Run Text="{Binding Value, ElementName=slider}" /> 
    </TextBlock> 
</StackPanel>
  1. Run the application. You will see a Slider control in the UI, along with a text that shows the current value, which...

How it works...

It works based on the current value. The property named Value, provides us with an integer, which denotes the current position. You can programmatically set it to move the slider thumb to a smaller or larger value.

The Minimum and Maximum properties denote the minimum and maximum value that the slider can accept. In our example, we set it to 0 (zero) and 100 (hundred), respectively.

The other control, TextBlock, in our example code, has a data binding to the Value property of the slider that we have in the XAML. It displays the current value of the slider in a plain text format.

There's more...

You can also enable the tick display in a slider control, to provide a better indication of the thumb placement. Use the TickPlacement property to turn on the tick markers. It has four values None, TopLeft, BottomRight, and Both. Let's add TickPlacement="BottomRight" in our previous slider control.

The TickFrequency property is used to set the range of possible values between 0 and 100. Let's add TickFrequency="20" to our code and then run the application again. You will see the following screen:

As shown in the preceding screenshot, you can see that some dots are added to the bottom of the slider. They represent the tick. As we have added TickFrequency as 20, it divided the entire slider range to 100/20 = 5 sections.

In general, moving the slider will not snap to the tick. Thus, you will observe the thumb placed between ticks. Use the IsSnapToTickEnabled property and set it to True, to make sure that the thumb always stays on the tick...

Using the Calendar control in your application

The Calendar control, part of the System.Windows.Controls namespace, allows you to create a visual calendar in WPF applications. It allows you to select a date or a collection of dates. As it inherits from the Control class, all common properties and events from Control class are available to it.

In this recipe, we will learn more about Calendar control and how to use that.

Getting ready

To get started with this recipe, let's create a WPF application project named CH02.CalendarDemo.

How to do it...

Follow these steps to add the basic controls to the main window:

  1. Open the MainWindow.xaml page.
  2. Inside the default Grid panel, add the tag <Calendar /> to create the basic calendar control in the application UI.
  3. To retrieve the date selected by the user, register the SelectedDatesChanged event to it, as shown in the following code snippet:
<Grid Margin="10"> 
    <Calendar SelectedDatesChanged="OnSelectedDateChanged"  
      HorizontalAlignment="Left" /> 
</Grid> 
  1. Add the associated event handler (OnSelectedDateChanged) in the code-behind class (MainWindow.xaml.cs), as shown in the following code, to retrieve the selected date and show it in a message box:
private void OnSelectedDateChanged(object sender,  
 SelectionChangedEventArgs e) 
{ 
    MessageBox.Show("You selected: " +  
      ((DateTime)e.AddedItems[0]).ToString("dd-MMM-yyyy")); 
} 
  1. Let's run the application. You will see the...

How it works...

WPF Calendar control provides you with the basic UI to begin the calendar integration in your application. The top two arrow-heads, allow you to navigate back and forth to other months and select the desired date from the calendar.

The navigation also supports year view and decade view, so, you can select the desired year and month very easily. Click on the month name (in our case, it's August 2017) present at the top, to navigate to the year view. When you are in the year view, it will show you the Jan–Dec month range, and clicking on the year will navigate you to the decade view where you can select the desired year.

There's more...

The Calendar control exposes many properties and events for you to customize the behavior and look of the control. Let's discuss this further.

The SelectionModes property

The SelectionMode property allows you to get or set the value indicating what kind of selections are allowed on the calendar. There are four values available, named None, SingleDate, SingleRange, and MultipleRange. The enum value SingleDate is default, and allows you to select only a single date. But when you want multi-selection, set it as MultipleRange:

<Calendar SelectionMode="MultipleRange" /> 

The DisplayDate property

The Calendar control allows you to set the start and end display dates. The DisplayDate property represents the current date to display; whereas, setting the DisplayDateStart and DisplayDateEnd properties limits you to select only the dates from the period ranging from the start date to the end date.

The following XAML code demonstrates how to set the DisplayDate, DisplayDateStart, and DisplayDateEnd properties in Calendar control:

<Calendar SelectionMode="MultipleRange" 
          DisplayDateStart="8/10/2017" 
          DisplayDateEnd="8/21/2017" 
          DisplayDate="8/16/2017" /> 

Run the application now to see the following output:

The DisplayMode property

The DisplayMode property allows you to select the format of the calendar, which can be a month, a year, or a decade. When you launch a basic calendar, by default, it shows the month view:

But a user can easily navigate from month to year to decade by clicking the header text of the Calendar control.

To change the display mode from code, you can set the DisplayMode property to Month, Year, or Decade:

<Calendar DisplayMode="Month" /> <!-- default mode --> 
<Calendar DisplayMode="Year" /> 
<Calendar DisplayMode="Decade" /> 

The user can initiate the downward transitions by clicking any of the calendar cells, and they can easily navigate from decade to year to month and select the correct date.

The BlackoutDates property

You can choose ranges of dates to be non-selectable despite being displayed. You can implement the same by using the calendar's BlackoutDates property, which takes a collection of CalendarDateRange objects.

The following Calendar control will block the date range from August 1st, 2017 to August 8th, 2017, and August 21st, 2017 to August 31st, 2017:

<Calendar> 
    <Calendar.BlackoutDates> 
        <CalendarDateRange Start="8/1/2017" End="8/8/2017" /> 
        <CalendarDateRange Start="8/21/2017" End="8/31/2017" /> 
    </Calendar.BlackoutDates> 
</Calendar> 

All non-selection dates are marked by a cross, as shown in the following screenshot:

Listing items in a Listbox control

In WPF, the ListBox control is used to display a list of items. Users can select one or more items from the list, depending on the SelectionMode specified.

In this recipe, we are going to learn how to create a ListBox control and use it in WPF applications.

Getting ready

Open your Visual Studio IDE and create a new WPF application project, called CH02.ListBoxDemo.

How to do it...

Adding a ListBox control in the UI is as easy as writing a <ListBox /> tag in any XAML page. But to hold the data in it, you will have to use its properties properly. Follow these steps to add a ListBox control with some static data:

  1. Open the MainWindow.xaml page of the WPF project.
  2. Under the default Grid panel, add the <ListBox></ListBox> tag to add the control.
  3. Add a few ListBoxItem inside the control, as shared here:
<ListBox x:Name="lstBox" 
         Width="120" Height="85" 
         Margin="10 10 20 5"> 
    <ListBoxItem Content="Item 1" /> 
    <ListBoxItem Content="Item 2" IsSelected="True" /> 
    <ListBoxItem Content="Item 3" /> 
    <ListBoxItem Content="Item 4" /> 
    <ListBoxItem Content="Item 5" /> 
</ListBox> 
  1. Add two buttons labelled + and - to perform the add and delete operations on the said...

How it works...

In the preceding example, the ListBox control contains five items as ListBoxItem. When you launch the application, by default, the second item is selected due to its property IsSelected being set to True.

The two buttons are used to add or delete items in the Listbox control. Click on the + button to trigger the OnAddItemClicked event, which will create a new instance of the ListBoxItem and add it to the ListBox control. Scroll the list to see the newly added entry. As the SelectedItem property of the ListBox is assigned with the latest item, it will now get selected, removing the previous selection.

Click on the - button to trigger the OnDeleteItemClicked event. This will get the current selected item, and, if it is not null, it will be removed from the ListBox control. The property SelectedIndex will set to 0 (zero), to select the first element after deletion.

There's more...

ListBox has numerous properties to perform specific actions. Let's learn a few of them. Later in this section, we will also cover how to add a customized ListBoxItem having additional UI controls.

Implementing multi selection

ListBox supports multi selection. By default, when the SelectionMode property is set to Single, it only accepts a single selection of items. If you set SelectionMode to Multiple, it will accept multi selection. The Extended mode allows you to perform single selection, but if you press the Ctrl key while selecting items, it will act as a multi selection.

Customizing the ListBoxItem with multiple controls

You can easily customize the ListBoxItem, by adding additional UI controls to it. Consider the following XAML code snippet, where we have added a ListBox, which has four ListBoxItem:

<ListBox Width="150" Margin="20 10 10 10"> 
    <ListBoxItem> 
        <StackPanel Orientation="Horizontal"> 
            <Rectangle Width="10" 
                       Height="10" 
                       Fill="Red" 
                       Margin="0 0 8 0" /> 
            <TextBlock Text="Red (#FFFF0000)" /> 
        </StackPanel> 
    </ListBoxItem> 
    <ListBoxItem IsSelected="True"> 
        <StackPanel Orientation="Horizontal"> 
            <Rectangle Width="10" 
                       Height="10" 
                       Fill="Green" 
                       Margin=&quot...

Providing options to select from a ComboBox

A ComboBox control is an items control and works like ListBox, but only one item from the list is selectable. A ListBox control by default lists multiple items on screen, but ComboBox control displays the scrollable list only on a user click. Thus, it takes up a lot less space.

This recipe will talk about ComboBox control and how to use it.

Getting ready

Begin with creating a new WPF application project, called CH02.ComboBoxDemo, using your Visual Studio IDE.

How to do it...

Follow these simple steps to add a ComboBox control in your application UI:

  1. Replace the default Grid with a StackPanel to host UI controls horizontally stacked.
  2. Add the following XAML code, inside the StackPanel, to have a simple ComboBox control with some items in it:
<ComboBox Width="150" Height="26" 
    Margin="10"> 
    <ComboBoxItem Content="Item 1" /> 
    <ComboBoxItem Content="Item 2" IsSelected="True" /> 
    <ComboBoxItem Content="Item 3" /> 
    <ComboBoxItem Content="Item 4" /> 
    <ComboBoxItem Content="Item 5" /> 
</ComboBox> 
  1. Add another ComboBox to have customized items, as shown in the following example code:
<ComboBox Width="150" Height="26" 
    Margin="10"> 
    <ComboBoxItem> 
        <StackPanel Orientation="Horizontal"> 
            <Rectangle Width=...

How it works...

Though a ComboBox control is like ListBox, it does not show the list of items by default. A user intervention is required to display the items. The UI of a ComboBox is a combination of three controls:

  • A TextBox, which displays the selected item
  • A Button, which is used to show or hide available items
  • A Popup, which displays a list of items inside a scrollable pane and gives the user the option to select one item from the available list

ComboBox contains a collection of ComboBoxItem. You can add those to its Items property. When you click on the arrow-head, the list of items will pop up in the screen, as demonstrated in the preceding screenshot. To preselect an item from code, set its IsSelected property to True.

You can also add custom contents to a ComboBoxItem to represent a better UI component. The second ComboBox in the preceding example, demonstrates how easy it is to customize the UI.

Just like ListBox, it also exposes SelectedItem, SelectedIndex, SelectedValue...

There's more...

The ComboBox control is not editable by default. But you can control this behavior to provide the user with the option to manually enter the desired value, directly in the ComboBox control. The IsEditable property is used to add this functionality. Set it to True, to change it to an editable ComboBox. Consider the following code:

<ComboBox Width="150" Height="26" 
    Margin="10" IsEditable="True"> 
    <ComboBoxItem Content="Item 1" /> 
    <ComboBoxItem Content="Item 2" IsSelected="True" /> 
    <ComboBoxItem Content="Item 3" /> 
    <ComboBoxItem Content="Item 4" /> 
    <ComboBoxItem Content="Item 5" /> 
</ComboBox> 

If you run the preceding code, you can see the following UI, where the control now allows you to enter text to it:

Adding a status bar to your window

The status bar is used to show various information about the current state of the application. You can use this to show cursor position, word counts, progress of tasks, and more. Generally, a status bar is placed at the bottom of the window whereas the menus, toolbars are placed at the top.

In this recipe, we will learn how to add a status bar in a WPF window.

Getting ready

To get started with the status bar, let's create a WPF application project called CH02.StatusBarDemo.

How to do it...

Once you create the WPF project, open the MainWindow.xaml page and follow these steps to add the StatusBar control to the window:

  1. Inside the Grid panel, add a StatusBar tag and set its Height to 26 and VerticalAlignment to Bottom.

  1. Now change its items panel template to host a Grid with five columns (we will discuss more about grid columns in the next chapter), as shown here:
<StatusBar.ItemsPanel> 
    <ItemsPanelTemplate> 
        <Grid> 
            <Grid.ColumnDefinitions> 
                <ColumnDefinition Width="Auto" /> 
                <ColumnDefinition Width="Auto" /> 
                <ColumnDefinition Width="*" /> 
                <ColumnDefinition Width="Auto" /> 
                <ColumnDefinition Width="Auto" /> 
            </Grid.ColumnDefinitions> 
        </Grid> 
    </ItemsPanelTemplate> 
</StatusBar.ItemsPanel> 
  1. Now, inside...

How it works...

In the preceding example, we have placed a plain text content Running Process... as a StatusBarItem inside the first column of the Grid. The second and fourth columns of the Grid contain a Separator control, having one pixel width. The fifth column contains a ProgressBar control, having an indeterminate state.

When you resize the window, the status bar will follow its parent to resize itself automatically and position it to the bottom of the window. Instead of Grid, you can also use DockPanel to dock the status bar at the bottom.

Adding a toolbar panel to perform quick tasks

In any windows-based application, you can find a toolbar, usually placed just below the main menu of a window. It contains a set of controls to provide easy access to common functions.

WPF offers you a ToolBarTray element to host one or more ToolBar controls, containing various UI controls. It provides you with some extra features, such as an automatic overflowing mechanism and a manual repositioning feature.

In this recipe, we will learn how to work with toolbars in a WPF application.

Getting ready

To begin with, open your Visual Studio IDE and create a new WPF application project called CH03.ToolBarDemo.

How to do it...

Once the project gets created, follow these steps to add a toolbar in the application window:

  1. Open the MainWindow.xaml page from the Solution Explorer.
  2. Now, replace the existing Grid with a DockPanel so that we can host the toolbar docking to the top of the window.
  3. Add a ToolBarTray element inside the DockPanel and dock it to Top.
  4. Add a ToolBar control inside the ToolBarTray and then add a few buttons inside it, as shown in the following XAML markup:
<ToolBarTray DockPanel.Dock="Top"> 
    <ToolBar> 
        <Button Content="B" FontWeight="Bold" 
                Width="20" 
                Click="OnBoldButtonClicked"/> 
        <Button Content="I" FontStyle="Italic" 
                Width="20"/> 
        <Button Width="20"> 
            <TextBlock Text="U"  
                       TextDecorations="Underline"/> 
        &lt...

How it works...

A ToolBarTray can contain one or more ToolBar controls. Each ToolBar control can contain one or more controls inside it. A ToolBar control can also remain empty. When you start adding other controls to it, the toolbar starts changing its size and position, based on the available space.

The controls placed inside a ToolBar can have its associated events registered. If you want, you can also use command bindings to have a more granular association between the view and the code.

In the preceding example, the first button, denoted by the character B, stands for applying Bold weightage to the associated TextBox. When you click it for the first time, the FontWeight property of the text will set it to Bold. When you click it again, it will set to Normal. By following the same logic, you can add a Click event for other buttons and a SelectionChange event for the combobox, as shown in the preceding example.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Gain a strong foundation in WPF features and patterns
  • Leverage the MVVM pattern to build decoupled, maintainable apps
  • Increase efficiency through Performance tuning and UI automation

Description

Windows Presentation Foundation (WPF) is Microsoft's development tool for building rich Windows client user experiences that incorporate UIs, media, and documents. With the updates in .NET 4.7, Visual Studio 2017, C# 7, and .NET Standard 2.0, WPF has taken giant strides and is now easier than ever for developers to use. If you want to get an in-depth view of WPF mechanics and capabilities, then this book is for you. The book begins by teaching you about the fundamentals of WPF and then quickly shows you the standard controls and the layout options. It teaches you about data bindings and how to utilize resources and the MVVM pattern to maintain a clean and reusable structure in your code. After this, you will explore the animation capabilities of WPF and see how they integrate with other mechanisms. Towards the end of the book, you will learn about WCF services and explore WPF's support for debugging and asynchronous operations. By the end of the book, you will have a deep understanding of WPF and will know how to build resilient applications.

Who is this book for?

The book is intended for developers who are relatively new to WPF (Windows Presentation Foundation), or those who have been working with WPF for some time, but want to get a deeper understanding of its foundation and concepts to gain practical knowledge. Basic knowledge of C# and Visual Studio is assumed.

What you will learn

  • Understand the fundamentals of WPF
  • Explore the major controls and manage element layout
  • Implement data binding
  • Create custom elements that lead to a particular implementation path
  • Customize controls, styles, and templates in XAML
  • Leverage the MVVM pattern to maintain a clean and reusable structure in your code
  • • Master practical animations
  • • Integrate WCF services in a WPF application
  • • Implement WPFs support for debugging and asynchronous operations
Estimated delivery fee Deliver to Brazil

Standard delivery 10 - 13 business days

R$63.95

Premium delivery 3 - 6 business days

R$203.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Feb 23, 2018
Length: 524 pages
Edition : 1st
Language : English
ISBN-13 : 9781788399807
Concepts :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Estimated delivery fee Deliver to Brazil

Standard delivery 10 - 13 business days

R$63.95

Premium delivery 3 - 6 business days

R$203.95
(Includes tracking information)

Product Details

Publication date : Feb 23, 2018
Length: 524 pages
Edition : 1st
Language : English
ISBN-13 : 9781788399807
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
R$50 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
R$500 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just R$25 each
Feature tick icon Exclusive print discounts
R$800 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just R$25 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total R$ 1,075.97
Windows Presentation Foundation 4.5 Cookbook
R$367.99
Windows Presentation Foundation Development Cookbook
R$367.99
Mastering Windows Presentation Foundation
R$339.99
Total R$ 1,075.97 Stars icon

Table of Contents

12 Chapters
WPF Fundamentals Chevron down icon Chevron up icon
Using WPF Standard Controls Chevron down icon Chevron up icon
Using WPF Standard Controls
Introduction
Using the TextBlock control to add plain text
Getting ready
How to do it...
How it works...
There's more...
Using Label to add other controls in text
Getting ready
How to do it...
How it works...
There's more...
Providing a user option to input text
Getting ready
How to do it...
How it works...
There's more...
Windows Clipboard support
Adding spellcheck support
Adding images to your application UI
Getting ready
How to do it...
How it works...
There's more...
Working with ready-to-use 2D shapes
Getting ready
How to do it...
How it works...
There's more...
Adding tooltips to show additional information
Getting ready
How to do it...
How it works...
There's more...
Adding a standard menu to the WPF application
Getting ready
How to do it...
How it works...
There's more...
Adding an access key to menus
Adding icons to menus
Adding checkable menu items
Adding click-event handlers to menus
Providing extra functionalities using the context menu
Getting ready
How to do it...
How it works...
Adding user options with radio buttons and checkboxes
Getting ready
How to do it...
How it works...
There's more...
Working with the progress bar control
Getting ready
How to do it...
How it works...
Using the Slider control to pick a numeric value
Getting ready
How to do it...
How it works...
There's more...
Using the Calendar control in your application
Getting ready
How to do it...
How it works...
There's more...
The SelectionModes property
The DisplayDate property
The DisplayMode property
The BlackoutDates property
Listing items in a Listbox control
Getting ready
How to do it...
How it works...
There's more...
Implementing multi selection
Customizing the ListBoxItem with multiple controls
Providing options to select from a ComboBox
Getting ready
How to do it...
How it works...
There's more...
Adding a status bar to your window
Getting ready
How to do it...
How it works...
Adding a toolbar panel to perform quick tasks
Getting ready
How to do it...
How it works...
Layouts and Panels Chevron down icon Chevron up icon
Working with Data Bindings Chevron down icon Chevron up icon
Using Custom Controls and User Controls Chevron down icon Chevron up icon
Using Styles, Templates, and Triggers Chevron down icon Chevron up icon
Using Resources and MVVM Patterns Chevron down icon Chevron up icon
Working with Animations Chevron down icon Chevron up icon
Using WCF Services Chevron down icon Chevron up icon
Debugging and Threading Chevron down icon Chevron up icon
Interoperability with Win32 and WinForm Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Most Recent
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3
(12 Ratings)
5 star 75%
4 star 0%
3 star 8.3%
2 star 8.3%
1 star 8.3%
Filter icon Filter
Most Recent

Filter reviews by




superticker Oct 04, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I was originally reluctant to buy a "cookbook" style textbook for introductory purposes because of the haphazard organization of the "recipes" listed inside. And _within_ a chapter, the organization is somewhat haphazard as expected. But the ordering of the chapters themselves is very well done and layered.The problem with an "integrated organization" is that too much material gets thrown at the reader at once making it hard to separate the trees from the forest. With the cookbook styling, each aspect is dissected separately bringing it into focus. And that makes learning easier in this complex context. Yes, the integration of the material between chapters is left more to the reader, but it's not too hard to connect the dots.The reader should have a command knowledge of C# and some prior experience with Visual Studio.The publisher has a website for downloading the examples. There's also a GitHub link with the latest code fixes to the examples.
Amazon Verified review Amazon
Ozkar de Grump Dec 26, 2020
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
Can't find any way to download examples. When I type them in by hand they won't compile. Checked for lexical errors till my eyes crossed. Checked for other errors until I despaired. If any one can help please do and I'll up my rating.
Amazon Verified review Amazon
Karl Y. Jul 11, 2020
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
This book was pretty informative up to about page 316 to 330. The text starts to narrow down to one single column of characters. I've been seeing that on another book. Doesn't Amazon proof the digital copy before they release it? I might have to try another book from another author.
Amazon Verified review Amazon
JBL Jun 20, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is great if you're just starting out with WPF. The content consists of code examples (both C# and XAML) with explanations in between. Overall, I would say the majority of this book focuses on the UI of an application.The physical condition of this book is good. The text is clear and easy to read and the pages don't stick together.While this is technically an intro book, there are a few tips here and there that could easily be overlooked if you're used to using the official Microsoft documentation.
Amazon Verified review Amazon
David R. Jan 14, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
WPF is a very large technology set and this book makes it easy to learn much of WPF. The author uses a logical progression and this book will serve as a good reference during application development. Just buy it and consume it.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela