Search icon CANCEL
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
€27.98 €39.99
Paperback
€49.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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

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 a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

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
€18.99 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
€189.99 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 €5 each
Feature tick icon Exclusive print discounts
€264.99 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 €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 144.97
Windows Presentation Foundation 4.5 Cookbook
€48.99
Windows Presentation Foundation Development Cookbook
€49.99
Mastering Windows Presentation Foundation
€45.99
Total 144.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

Top Reviews
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
Top Reviews

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
Amazon Customer May 11, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Kunal does a fantastic job in laying down a strong foundation for laerning WPF in the first few chapters and goes on to deliver a solid, well-rounded book that covers all the bases. If you have always wanted to get into Windows Presentation Foundation, then you should consider reading his book.Personally, I like the cookbook approach. This book contains many "recipes" allowing the reader to become familiar with the topic. Later chapters are a bit more in depth, showing you how to work with animations and discussing MVVM patterns. I really enjoyed the spread of the chapters, covering a nice portion of WPF.Lastly, Kunal is one of the few authors that delivers superb screenshots... annotating them well so that there is no ambiguity in his explaination of the topic. For me, not professionally having worked much with WPF in the past (apart from the odd pet project), this book definitely belongs on my bookshelf.
Amazon Verified review Amazon
深淵の機械 Aug 15, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I've found this book extremely helpful as a new Developer. Unlike many other similar titles, it's clear, concise and easy to follow.
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
Alvin Ashcraft Mar 08, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I was the technical reviewer of this book and would like to provide a review of it from my perspective.This "cookbook" style WPF book is a great resource for software developers with a mid-level (or less) understanding of WPF development. More experienced developers will probably still learn a few things, but most of the content is best for those with less experience on the platform. The cookbook format divides lessons into "recipes" with a familiar and consistent approach to teaching the core concepts of WPF development.Every concept that is needed to get up and going with WPF is covered in the book, from controls to binding to styles & templates to MVVM concepts. Later chapters cover more advanced topics like calling WCF services, threading and interop.There are not many current titles for WPF developers out there. I was really happy to see Packt decided to put an updated resource out for today's desktop Windows developer.
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 included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.