100% found this document useful (1 vote)
25 views

Exploring Windows Presentation Foundation: With Practical Applications in .NET 5 Taurius Litvinavicius - Quickly download the ebook in PDF format for unlimited reading

The document promotes a collection of eBooks available for download at textbookfull.com, including titles on Windows Presentation Foundation, Blazor, mobile development with .NET, and more. Each book is linked for easy access and covers various topics related to software development and engineering. The document also includes details about the authors and a brief overview of the content structure for one of the highlighted books.

Uploaded by

boreklucre
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
25 views

Exploring Windows Presentation Foundation: With Practical Applications in .NET 5 Taurius Litvinavicius - Quickly download the ebook in PDF format for unlimited reading

The document promotes a collection of eBooks available for download at textbookfull.com, including titles on Windows Presentation Foundation, Blazor, mobile development with .NET, and more. Each book is linked for easy access and covers various topics related to software development and engineering. The document also includes details about the authors and a brief overview of the content structure for one of the highlighted books.

Uploaded by

boreklucre
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Explore the full ebook collection and download it now at textbookfull.

com

Exploring Windows Presentation Foundation: With


Practical Applications in .NET 5 Taurius
Litvinavicius

https://textbookfull.com/product/exploring-windows-
presentation-foundation-with-practical-applications-in-
net-5-taurius-litvinavicius/

OR CLICK HERE

DOWLOAD EBOOK

Browse and Get More Ebook Downloads Instantly at https://textbookfull.com


Click here to visit textbookfull.com and download textbook now
Your digital treasures (PDF, ePub, MOBI) await
Download instantly and pick your perfect format...

Read anywhere, anytime, on any device!

Exploring Blazor: Creating Hosted, Server-side, and


Client-side Applications with C# Taurius Litvinavicius

https://textbookfull.com/product/exploring-blazor-creating-hosted-
server-side-and-client-side-applications-with-c-taurius-litvinavicius/

textbookfull.com

Mobile Development with NET Build cross platform mobile


applications with Xamarin Forms 5 and ASP NET Core 5 2nd
Edition Can Bilgin
https://textbookfull.com/product/mobile-development-with-net-build-
cross-platform-mobile-applications-with-xamarin-forms-5-and-asp-net-
core-5-2nd-edition-can-bilgin/
textbookfull.com

Pro ASP NET Core Identity Under the Hood with


Authentication and Authorization in ASP NET Core 5 and 6
Applications 1st Edition Adam Freeman
https://textbookfull.com/product/pro-asp-net-core-identity-under-the-
hood-with-authentication-and-authorization-in-asp-net-
core-5-and-6-applications-1st-edition-adam-freeman/
textbookfull.com

Foundation Engineering: Geotechnical Principles and


Practical Applications 1st Edition Richard Handy

https://textbookfull.com/product/foundation-engineering-geotechnical-
principles-and-practical-applications-1st-edition-richard-handy/

textbookfull.com
Windows 11 Mastery: From Foundation to Mastery Kameron
Hussain

https://textbookfull.com/product/windows-11-mastery-from-foundation-
to-mastery-kameron-hussain/

textbookfull.com

Applied Cryptography in .NET and Azure Key Vault: A


Practical Guide to Encryption in .NET and .NET Core 1st
Edition Stephen Haunts
https://textbookfull.com/product/applied-cryptography-in-net-and-
azure-key-vault-a-practical-guide-to-encryption-in-net-and-net-
core-1st-edition-stephen-haunts/
textbookfull.com

Pro C 9 with NET 5 Foundational Principles and Practices


in Programming Tenth Edition Andrew Troelsen Phillip
Japikse
https://textbookfull.com/product/pro-c-9-with-net-5-foundational-
principles-and-practices-in-programming-tenth-edition-andrew-troelsen-
phillip-japikse/
textbookfull.com

Pro C 9 with NET 5 Foundational Principles and Practices


in Programming Tenth Edition Andrew Troelsen Phillip
Japikse
https://textbookfull.com/product/pro-c-9-with-net-5-foundational-
principles-and-practices-in-programming-tenth-edition-andrew-troelsen-
phillip-japikse-2/
textbookfull.com

Pro .NET 5 Custom Libraries: Implementing Custom .NET Data


Types 1st Edition Roger Villela

https://textbookfull.com/product/pro-net-5-custom-libraries-
implementing-custom-net-data-types-1st-edition-roger-villela/

textbookfull.com
Exploring
Windows
Presentation
Foundation
With Practical Applications in .NET 5

Taurius Litvinavicius
Exploring Windows
Presentation
Foundation
With Practical
Applications in .NET 5

Taurius Litvinavicius
Exploring Windows Presentation Foundation: With Practical Applications
in .NET 5

Taurius Litvinavicius
Jonava, Lithuania

ISBN-13 (pbk): 978-1-4842-6636-6 ISBN-13 (electronic): 978-1-4842-6637-3


https://doi.org/10.1007/978-1-4842-6637-3

Copyright © 2021 by Taurius Litvinavicius


This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or
part of the material is concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way,
and transmission or information storage and retrieval, electronic adaptation, computer software,
or by similar or dissimilar methodology now known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark
symbol with every occurrence of a trademarked name, logo, or image we use the names, logos,
and images only in an editorial fashion and to the benefit of the trademark owner, with no
intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if
they are not identified as such, is not to be taken as an expression of opinion as to whether or not
they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of
publication, neither the authors nor the editors nor the publisher can accept any legal
responsibility for any errors or omissions that may be made. The publisher makes no warranty,
express or implied, with respect to the material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Smriti Srivastava
Development Editor: Laura Berendson
Coordinating Editor: Shrikant Vishwakarma
Cover designed by eStudioCalamar
Cover image designed by Pexels
Distributed to the book trade worldwide by Springer Science+Business Media LLC, 1 New York
Plaza, Suite 4600, New York, NY 10004. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail
[email protected], or visit www.springeronline.com. Apress Media, LLC is a
California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc
(SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail [email protected]; for
reprint, paperback, or audio rights, please e-mail [email protected].
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook
versions and licenses are also available for most titles. For more information, reference our Print
and eBook Bulk Sales web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available
to readers on GitHub via the book’s product page, located at www.apress.com/978-­1-­4842-­6636-­6.
For more detailed information, please visit http://www.apress.com/source-­code.
Printed on acid-free paper
Table of Contents
About the Author��������������������������������������������������������������������������������vii

About the Technical Reviewer�������������������������������������������������������������ix


Introduction�����������������������������������������������������������������������������������������xi

Chapter 1: Getting Started��������������������������������������������������������������������1


Button and Click Event������������������������������������������������������������������������������������������1
Window and Page�������������������������������������������������������������������������������������������������6
Text Box���������������������������������������������������������������������������������������������������������������12
Message Box�������������������������������������������������������������������������������������������������������14
Quick Example����������������������������������������������������������������������������������������������������18
Quick Exercise����������������������������������������������������������������������������������������������������22

Chapter 2: Events�������������������������������������������������������������������������������33
Application Events����������������������������������������������������������������������������������������������33
Mouse Events������������������������������������������������������������������������������������������������������34
Keyboard Events�������������������������������������������������������������������������������������������������38
Window Events���������������������������������������������������������������������������������������������������39
Quick Example����������������������������������������������������������������������������������������������������41
Quick Exercise����������������������������������������������������������������������������������������������������44

iii
Table of Contents

Chapter 3: UI Elements�����������������������������������������������������������������������51


Progress Bar�������������������������������������������������������������������������������������������������������51
Tabs���������������������������������������������������������������������������������������������������������������������55
Radio Button�������������������������������������������������������������������������������������������������������56
Check Box�����������������������������������������������������������������������������������������������������������59
Slider�������������������������������������������������������������������������������������������������������������������62
Image������������������������������������������������������������������������������������������������������������������64
Media Element����������������������������������������������������������������������������������������������������65
Menu�������������������������������������������������������������������������������������������������������������������70
List View��������������������������������������������������������������������������������������������������������������71
Web Browser�������������������������������������������������������������������������������������������������������74
Canvas����������������������������������������������������������������������������������������������������������������75
Generate Elements in C#�������������������������������������������������������������������������������������78
Background Tasks�����������������������������������������������������������������������������������������������81

Chapter 4: Files�����������������������������������������������������������������������������������85
Pick and Save�����������������������������������������������������������������������������������������������������85
Quick Example����������������������������������������������������������������������������������������������������89
Quick Exercise����������������������������������������������������������������������������������������������������95

Chapter 5: MVVM������������������������������������������������������������������������������101
Element to Element Binding������������������������������������������������������������������������������103
Introducing ViewModel�������������������������������������������������������������������������������������104
Implementing Models���������������������������������������������������������������������������������������109
Quick Example��������������������������������������������������������������������������������������������������116
Quick Exercise��������������������������������������������������������������������������������������������������136
Solution�������������������������������������������������������������������������������������������������������141

iv
Table of Contents

Chapter 6: Styles������������������������������������������������������������������������������151
Window Size and Other Sizes���������������������������������������������������������������������������151
Style������������������������������������������������������������������������������������������������������������������160
Quick Example��������������������������������������������������������������������������������������������������177
Quick Exercise��������������������������������������������������������������������������������������������������208
Solution�������������������������������������������������������������������������������������������������������210

Index�������������������������������������������������������������������������������������������������223

v
About the Author
Taurius Litvinavicius is a businessman and
technology expert based in Lithuania who
has worked with various organizations in
building and implementing projects in
software development, sales, and other fields
of business. He is responsible for technological
improvements, development of new features,
and general management. Taurius is also the
director at the Conficiens solutio consulting
agency where he supervises the development
and maintenance of various projects and
activities.

vii
About the Technical Reviewer
Carsten Thomsen is a back-end developer
primarily but working with smaller front-
end bits as well. He has authored and
reviewed a number of books, and created
numerous Microsoft Learning courses, all to
do with software development. He works as
a freelancer/contractor in various countries
in Europe, using Azure, Visual Studio, Azure
DevOps, and GitHub as some of his tools.
Being an exceptional troubleshooter, asking
the right questions, including the less logical
ones, in a most logical to least logical fashion, he also enjoys working with
architecture, research, analysis, development, testing, and bug fixing.
Carsten is a very good communicator with great mentoring and team lead
skills and great skills researching and presenting new material.

ix
Introduction
In this book, you will find lots of information about Windows Presentation
Foundation (WPF) which will help you get started with it. Alongside the
explanations of features, you will find use case examples and exercise
assignments for you to practice what you have learned.
The first chapter will provide you with a basic introduction to the
WPF. That will include handling button click event, window handling,
accessing text box inputs, and a few more things. In the next chapter, you
will see some generic events; some of them are related to the window,
some to the mouse, and some to other things. The third chapter will
cover various UI elements in WPF; it will also be useful to you for future
reference. It is important to read and understand the first chapter, but in
case you are in a hurry, you may skip the second and third chapters and
only use them as reference later.
The fourth chapter will show you how to handle files in the WPF
interface, and with that, it will provide some use cases to study. At this
point, the examples will incorporate quite a few items from the previous
chapters. Then in the fifth, you will see how the MVVM structure can be
implemented – the explanation will be a practical one; this should help
you understand MVVM quicker. The final chapter will cover the styling
aspects of WPF, but with that, it will also show examples that incorporate
most things that you can find in the previous chapters. Once again, if
you are rushing to get started with WPF and do not have too much time,
you may skip the MVVM chapter. But it would be a good idea to take a
look at it later, as it is useful to understand what MVVM is and how it is
implemented.

xi
CHAPTER 1

Getting Started
Windows Presentation Foundation (WPF) has many features and many
arrangements you can choose from, but there are a few crucial things that
you have to know before going anywhere else. For any user interaction
to be viable in WPF, you need to understand how to use the methods,
and with that, you also need to understand how to set properties on the
elements. In this chapter, we will begin with only a handful of them, and in
Chapter 3, you will see many more to choose from, and they function in a
very similar way. Before going further, you should also understand how to
establish and then display or close windows and how to display quick and
simple alert messages.

Button and Click Event


Probably the most important element in WPF is the button, and probably
the most important event is the click event. Now, the main three things in
WPF are elements (e.g., button), events, and names of the elements. The
first thing you will learn about is a button, but for it to make sense, you will
also need to look at something called text block and label.

© Taurius Litvinavicius 2021 1


T. Litvinavicius, Exploring Windows Presentation Foundation,
https://doi.org/10.1007/978-1-4842-6637-3_1
Chapter 1 Getting Started

Figure 1-1. File layout in the project

To begin with, we will work with the MainWindow.xaml source


file, which is where the XAML code for the window and its elements go
(Figure 1-1). MainWindow.xaml.cs is what is called a code-behind file;
that is where the C# code for that window goes. In the next section, you
will learn how to add more windows and navigate between them.

Figure 1-2. Toolbox in design view editor

2
Chapter 1 Getting Started

Once you get into the MainWindow.xaml code, you will see a designer
view. Although you can set various properties in XAML, it is best to drag
and drop from the toolbox (Figure 1-2) and then move things around, expand
them, and do other things in the designer. Once you drag and drop something
onto the designer view, the XAML code for that element will be generated.

Figure 1-3. Window view for the example

This is what our example (see Figure 1-3) will look like (after the
buttons are clicked).

Listing 1-1. XAML code for the MainWindow.xaml

<Window x:Class="WpfApp3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/
presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/
blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-
compatibility/2006"

3
Chapter 1 Getting Started

        xmlns:local="clr-namespace:WpfApp3"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Button x:Name="bt1" Content="first option"
HorizontalAlignment="Left" Margin="350,163,0,0"
VerticalAlignment="Top" Width="101"/>
        <TextBlock x:Name="textblock1"
HorizontalAlignment="Left" Margin="350,198,0,0"
TextWrapping="Wrap" VerticalAlignment="Top"
Width="101"/>

        <Button Click="Button_Click" Content="second option"


HorizontalAlignment="Left" Margin="350,229,0,0"
VerticalAlignment="Top" Width="101"/>
        <Label x:Name="label1" Content=""
HorizontalAlignment="Left" Margin="350,254,0,0"
VerticalAlignment="Top" Width="101"/>
    </Grid>
</Window>

This is the XAML code (Listing 1-1) for MainWindow.xaml; all the
elements go into the Grid element. The first element in the grid is a Button.
In it, we have a name property (you will see why we need it in the C# code);
after that, we have Content, which is the text displayed in the button.
After that, two very important properties are HorizontalAlignment and
VerticalAlignment, which are important because they determine the
alignment, and with that, you can use margins accordingly.
The next element is the TextBlock which is used to display text – the
crucial part here is the name, as that will be the reference point in C#. With
that, you can also see TextWrapping – if set, it will wrap the text onto a new
line; if not set, the default value will be used (NoWrap) and the text will be
displayed in a single line.

4
Chapter 1 Getting Started

Another Button, similar to the first one, but with no name specified.
Instead, we have the Click property which has a value of Button_Click –
this will correspond with the event method name in C#. So, you will
basically see two ways of declaring an event.
Finally, we have a label, which is an element very similar to a
TextBlock. But the label has fewer options in terms of customization.

Listing 1-2. C# code for MainWindow.xaml.cs

public partial class MainWindow : Window


    {
        public MainWindow()
        {
            InitializeComponent();
            bt1.Click += Bt1_Click;
        }

        private void Bt1_Click(object sender, RoutedEventArgs e)


        {
            textblock1.Text = "button works 1";
        }

        private void Button_Click(object sender,


RoutedEventArgs e)
        {
            label1.Content = "button works 2";
        }
    }

In the C# code (code-behind) (see Listing 1-2), you can first see the
constructor method for the window class. In it, we declare the button click
event for the first button. In the code, the first event is for the first button and
the second for the second button. To set a display value for the TextBlock, you
need to set the Text property, but for the label, you set the Content property.

5
Chapter 1 Getting Started

W
 indow and Page
In WPF there are two main view options – one is window, and the other is
page. Another option may be tabs, or you may simply change visibility of
grids and other containers, but that will be covered in the next chapters
(Chapters 3 and 6).
Both window and page will have XAML part and C# part (code-­behind).
The main difference is how they are displayed and how the user navigates
between them.

Figure 1-4. Adding Window file in WPF project

6
Chapter 1 Getting Started

To create a new window, you need to right-click your project (or folder
in which you will place the file) and then go to add and choose Window
(WPF) (see Figure 1-4). Alternatively, you can find this option in “New Item”.

Listing 1-3. XAML code in MainWindow.xaml

<Window x:Class="WpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/
presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/
blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-­
compatibility/2006"
        xmlns:local="clr-namespace:WpfApp"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Button x:Name="bt1" Content="window 1"
HorizontalAlignment="Left" Margin="246,118,0,0"
VerticalAlignment="Top" Width="75"/>

    </Grid>
</Window>

The XAML part of a window (See Listing 1-3) will contain all the
markup for your elements and the window itself. By default, a window
will contain a grid and that is where you should place your elements – you
cannot do that in the window itself. In the default window, everything from
x:Class to mc:Ignorable should not be modified; otherwise, it may break.
You may change the title property (which appears at the top-left corner of
a window), and you can change the height and width properties. There are
many more things that you can do with a window, and some of them will
be covered in the last chapter of this book.

7
Chapter 1 Getting Started

Listing 1-4. MainWindow.xaml.cs contents

public MainWindow()
        {
            InitializeComponent();
            bt1.Click += Bt1_Click;

        }

        private void Bt1_Click(object sender, RoutedEventArgs e)


        {
            Window w1 = new Window1();
            w1.Show();
        }

By default, the application will open your main window


(MainWindow), but later, you can close it and/or open more windows,
and there are two ways of doing this. In this particular example, we have
another window created, and it is named Window1. You can see that on
button click event (see Listing 1-4), we construct and establish a variable
for that new window. To display it, we execute the Show method. This
will display the new window, but it will not close the existing one and will
allow to interact with the existing window. An alternative to that is to open
a window by using the ShowDialog method; this will freeze the existing
window and will only allow the user to interact with the new one. To close
the current window, you will need to use the this.Close() method or you
can control by reference; in this case, it would be w1.Close().
It is also important to understand the constructor method for the
window. By default, you have the InitializeComponent method which
initializes all the elements declared in the window. So, if you want to
set properties (e.g., set text to text block), you need to do all that after
InitializeComponent has occurred.
The Page is not as stand-alone as a Window; instead, you use pages to
establish some navigation inside a Window.

8
Chapter 1 Getting Started

Figure 1-5. File layout in the project

In this example, we have added two new files (see Figure 1-5) – Pages.

Figure 1-6. First state of the view (nothing clicked)

Initially, you will see an empty window like this (Figure 1-6).

9
Chapter 1 Getting Started

Figure 1-7. Second state of the view (“To page 1” button clicked)

After the button is clicked, a page will be displayed (see Figure 1-7).
If the second button is clicked, the first page will be replaced with the
second one.

Listing 1-5. MainWindow.xaml contents

<Grid>
        <Frame x:Name="fr"   Margin="0,0,0,66" NavigationUI
Visibility="Hidden"/>
        <Button Content="To page 1" Click="Button_Click"
HorizontalAlignment="Left" Margin="321,406,0,0"
VerticalAlignment="Top" Height="28" Width="79"/>
        <Button Content="To page 2" Click="Button_Click_1"
HorizontalAlignment="Left" Margin="400,406,0,0"
VerticalAlignment="Top" Height="28" Width="79"/>
    </Grid>

10
Chapter 1 Getting Started

In your window (see Listing 1-5) in which you want to display pages,
you will need a Frame element – that is where a page is displayed.
You need to set an appropriate size, establish a name, and then set
NavigationUIVisibility to Hidden. The last one is not important from
a functional perspective, but if not set, it would display a navigation bar,
similar to what a browser might have.

Listing 1-6. Events in MainWindow.xaml.cs

private void Button_Click(object sender, RoutedEventArgs e)


        {
            fr.Content = new Page1();
        }

        private void Button_Click_1(object sender,


RoutedEventArgs e)
        {
            fr.Content = new Page2();
        }

Navigating to a page is quite simple here (See Listing 1-6); you just
need to set the Content property of the Frame element.

Listing 1-7. Constructor method for Page1 (Page1.xaml.cs)

public Page1()
        {
            InitializeComponent();
        }

A Page has a constructor (see Listing 1-7) just like a Window,


and inside that, you will find the same arrangement with the
InitializeComponent method.

11
Chapter 1 Getting Started

Text Box
There are two basic interactive elements in WPF – the first one you already
know, which is a button, and the second one is the text box. In this book,
you will see more elements in the third chapter, but this will be your
starting point in understanding the input elements.

Figure 1-8. Window view for the example

Listing 1-8. MainWindow.xaml contents


<Grid>
        <Label Content="input:" HorizontalAlignment="Left"
Margin="328,100,0,0" VerticalAlignment="Top"
Width="106"/>
        <TextBox x:Name="tb1" HorizontalAlignment="Left"
Height="23" Margin="328,131,0,0" TextWrapping="Wrap"
VerticalAlignment="Top" Width="120"/>
        <Label Content="output:" HorizontalAlignment="Left"
Margin="328,164,0,0" VerticalAlignment="Top"
Width="106"/>

12
Chapter 1 Getting Started

        <TextBox x:Name="output2" HorizontalAlignment="Left"


Height="22" Margin="328,230,0,0" TextWrapping="Wrap"
VerticalAlignment="Top" Width="120"/>
        <Label x:Name="output1" Content=""
HorizontalAlignment="Left" Margin="328,199,0,0"
VerticalAlignment="Top" Width="106"/>
        <Button Click="Button_Click" Content="test"
HorizontalAlignment="Left" Margin="328,75,0,0"
VerticalAlignment="Top" Width="120"/>
    </Grid>

In this case, we have six elements (see Figure 1-8 and Listing 1-8) in
the XAML (the grid is in the window). The first label simply has some
static text, the second element is a text box, and a text box needs a name
for referencing in C#. After that, we have another static label and then we
have another text box with a name. There is also another label with a name
(it will be used from C#) and finally a button with an event. Notice, in this
case, the event is declared in XAML; therefore, you will not see it declared
in the C# code. The idea here is to enter something into the input box (tb1)
and output the value in the label (output1) and text box (output2).
If you want to have multiple lines in your text box input, you need to set
the AcceptsReturn property to True. Also, by default, the text box does not
accept tab input; if you want that, you will need to set AcceptsTab="True".

Listing 1-9. Button click event

private void Button_Click(object sender, RoutedEventArgs e)


        {
            output1.Content = tb1.Text + " 1";
            output2.Text = tb1.Text + " 2";
        }

13
Chapter 1 Getting Started

This is the event on button click in the C# part (see Listing 1-9). Now,
the output1 is a label and a label has the property Content, which is what
you assign to display something. On the other hand, text box has the Text
property, which will hold the input and can also be assigned to display
something. The most important thing in any input element is to know
which property holds the value – in this case, it is quite easy to find, but
later, you will see some elements that are a bit more tricky.

Message Box
Message box is a great way to display basic notifications and alerts
to the user; it is simple to use and can be a great safeguard on some
occasions. Now, we will look at how it is implemented, but before that,
you have to know about the possible arrangements of this feature. There
are four default options in a message in terms of the buttons it may
contain. Each button, when clicked, will close the box and return a result
(MessageBoxResult). Later in this book, you will learn how to make your
own custom message box (refer to Chapter 6).

Figure 1-9. Simple message box

14
Chapter 1 Getting Started

The first variation (see Figure 1-9) is a message box with an OK


button. This option should not be used to return a value, as there is only
one option for that. However, this would be the most commonly used
option, as it is best for displaying simple warnings (e.g., wrong password,
disconnected).

Figure 1-10. OK/Cancel message box

This option (see Figure 1-10) is best for when the user has to leave (or
clear) something. In those arrangements, this would be the last chance for
them to avoid data loss.

Figure 1-11. Yes/No message box

The Yes/No option (see Figure 1-11) is very similar to OK/Cancel,


as it can be used for the same purposes (e.g., “Do you want to leave this
window?”). However, the return values will be different.

15
Chapter 1 Getting Started

Figure 1-12. Yes/No/Cancel message box

The final option (see Figure 1-12) is the most elaborate one, and it
can be used in various scenarios. It is unlikely to be the most common
type, but it is the only one that has three buttons, hence three different
possible outcomes. We will look at a code example of this message box
implemented.

Listing 1-10. XAML code in MainWindow.xaml

<Grid>
        <Button x:Name="mbtestbt" Content="test"
HorizontalAlignment="Left" Margin="360,179,0,0"
VerticalAlignment="Top" Width="75"/>

    </Grid>

In the XAML part (See Listing 1-10), we only have one button defined.
We also have a name for the button, which we will use to establish an
event. Do remember that an event like this could be defined on the button
in the XAML.

16
Chapter 1 Getting Started

Listing 1-11. Contents of MainWindow.xaml.cs

public MainWindow()
        {
            InitializeComponent();
            mbtestbt.Click += Mbtestbt_Click;
        }

        private void Mbtestbt_Click(object sender,


RoutedEventArgs e)
        {
            MessageBoxResult mbresult = MessageBox.Show("test
box", "tb", MessageBoxButton.YesNoCancel);
             MessageBox.Show(mbresult.ToString());
            if (MessageBoxResult.Yes == mbresult)
            {
                MessageBox.Show("yes clicked!");
            }
        }

In the window class constructor (see Listing 1-11), we establish our


click event, and the event is where the interesting part begins. First, we
need to show the message box, and that is done using MessageBox.Show,
which in this case has a return value – MessageBoxResult. The Show
method has other variations as well, and it does not have to return a value
to be used; it also does not have to specify other values. In this example,
we actually display the result that user chose, and then you can see an if
statement where we check for result values being Yes.

17
Chapter 1 Getting Started

Q
 uick Example
To wrap things up with the basics, we have a very basic example. This will
show you how some of these elements and feature of WPF can interact
together.

Figure 1-13. The window view for the example

As you can see (see Figure 1-13), we have a simple registration form.
We will not look at the full functionality of such an arrangement, but you

18
Chapter 1 Getting Started

will see how these elements can work to create something useful. The
Generate button will generate a five-digit password, and the Copy button
will copy it to the clipboard. On the Submit button, we do send the data
anywhere, but we do check for the password to be longer than three
characters (i.e., at least four characters).

Listing 1-12. Contents of MainWindow.xaml in the example

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/
presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/
blend/2008"
        ­xmlns:mc="http://schemas.openxmlformats.org/markup-­
compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="Registration window" Height="450" Width="415">
    <Grid HorizontalAlignment="Center" Width="415">
        <Label Content="Full name" HorizontalAlignment="Center"
Margin="0,62,0,0" VerticalAlignment="Top" Width="147"/>
        <TextBox x:Name="tb_fullname"
HorizontalAlignment="Left" Margin="134,93,0,0"
TextWrapping="Wrap" VerticalAlignment="Top"
Width="120"/>
        <Label Content="Email" HorizontalAlignment="Center"
Margin="0,136,0,0" VerticalAlignment="Top"
Width="147"/>
        <TextBox x:Name="tb_email" HorizontalAlignment="Left"
Margin="134,167,0,0" TextWrapping="Wrap"
VerticalAlignment="Top" Width="120"/>

19
Chapter 1 Getting Started

        <Label Content="Password" HorizontalAlignment="Center"


Margin="0,207,0,0" VerticalAlignment="Top"
Width="147"/>
        <TextBox x:Name="tb_password"
HorizontalAlignment="Left" Margin="134,238,0,0"
TextWrapping="Wrap" VerticalAlignment="Top"
Width="120"/>
        <Button x:Name="bt_copy" Click="bt_copy_Click"
Content="Copy" HorizontalAlignment="Left"
Margin="254,238,0,0" VerticalAlignment="Top" Width="61"
Padding="0" Height="18"/>
        <Button x:Name="bt_generate" Click="bt_generate_
Click" Content="Generate" HorizontalAlignment="Left"
Margin="158,261,0,0" VerticalAlignment="Top" Width="75"
Height="19"/>
        <Button x:Name="bt_submit" Click="bt_submit_
Click" Content="Submit" HorizontalAlignment="Left"
Margin="158,335,0,0" VerticalAlignment="Top" Width="76"
Height="18"/>

    </Grid>
</Window>

The first thing you may notice in the XAML code (See Listing 1-12)
is the window title, and then you can see that the width is set to 415. The
labels in this case are simply for displaying static values. After that, notice
how the text boxes and buttons are named. The text boxes start with tb,
and the buttons start with bt; this helps when you have to type in the
names in the C# code. Also, when you have a name for the button and
create an event through XAML, a very appropriate name for the event will
be generated.

20
Exploring the Variety of Random
Documents with Different Content
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the free


distribution of electronic works, by using or distributing this work (or
any other work associated in any way with the phrase “Project
Gutenberg”), you agree to comply with all the terms of the Full
Project Gutenberg™ License available with this file or online at
www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand, agree
to and accept all the terms of this license and intellectual property
(trademark/copyright) agreement. If you do not agree to abide by all
the terms of this agreement, you must cease using and return or
destroy all copies of Project Gutenberg™ electronic works in your
possession. If you paid a fee for obtaining a copy of or access to a
Project Gutenberg™ electronic work and you do not agree to be
bound by the terms of this agreement, you may obtain a refund
from the person or entity to whom you paid the fee as set forth in
paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only be


used on or associated in any way with an electronic work by people
who agree to be bound by the terms of this agreement. There are a
few things that you can do with most Project Gutenberg™ electronic
works even without complying with the full terms of this agreement.
See paragraph 1.C below. There are a lot of things you can do with
Project Gutenberg™ electronic works if you follow the terms of this
agreement and help preserve free future access to Project
Gutenberg™ electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright law
in the United States and you are located in the United States, we do
not claim a right to prevent you from copying, distributing,
performing, displaying or creating derivative works based on the
work as long as all references to Project Gutenberg are removed. Of
course, we hope that you will support the Project Gutenberg™
mission of promoting free access to electronic works by freely
sharing Project Gutenberg™ works in compliance with the terms of
this agreement for keeping the Project Gutenberg™ name associated
with the work. You can easily comply with the terms of this
agreement by keeping this work in the same format with its attached
full Project Gutenberg™ License when you share it without charge
with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the
terms of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.

1.E. Unless you have removed all references to Project Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project Gutenberg™
work (any work on which the phrase “Project Gutenberg” appears,
or with which the phrase “Project Gutenberg” is associated) is
accessed, displayed, performed, viewed, copied or distributed:
This eBook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this eBook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is derived


from texts not protected by U.S. copyright law (does not contain a
notice indicating that it is posted with permission of the copyright
holder), the work can be copied and distributed to anyone in the
United States without paying any fees or charges. If you are
redistributing or providing access to a work with the phrase “Project
Gutenberg” associated with or appearing on the work, you must
comply either with the requirements of paragraphs 1.E.1 through
1.E.7 or obtain permission for the use of the work and the Project
Gutenberg™ trademark as set forth in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is posted


with the permission of the copyright holder, your use and distribution
must comply with both paragraphs 1.E.1 through 1.E.7 and any
additional terms imposed by the copyright holder. Additional terms
will be linked to the Project Gutenberg™ License for all works posted
with the permission of the copyright holder found at the beginning
of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files containing a
part of this work or any other work associated with Project
Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute this


electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the Project
Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or
expense to the user, provide a copy, a means of exporting a copy, or
a means of obtaining a copy upon request, of the work in its original
“Plain Vanilla ASCII” or other form. Any alternate format must
include the full Project Gutenberg™ License as specified in
paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™ works
unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or providing


access to or distributing Project Gutenberg™ electronic works
provided that:

• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project Gutenberg™


electronic work or group of works on different terms than are set
forth in this agreement, you must obtain permission in writing from
the Project Gutenberg Literary Archive Foundation, the manager of
the Project Gutenberg™ trademark. Contact the Foundation as set
forth in Section 3 below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on, transcribe
and proofread works not protected by U.S. copyright law in creating
the Project Gutenberg™ collection. Despite these efforts, Project
Gutenberg™ electronic works, and the medium on which they may
be stored, may contain “Defects,” such as, but not limited to,
incomplete, inaccurate or corrupt data, transcription errors, a
copyright or other intellectual property infringement, a defective or
damaged disk or other medium, a computer virus, or computer
codes that damage or cannot be read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for


the “Right of Replacement or Refund” described in paragraph 1.F.3,
the Project Gutenberg Literary Archive Foundation, the owner of the
Project Gutenberg™ trademark, and any other party distributing a
Project Gutenberg™ electronic work under this agreement, disclaim
all liability to you for damages, costs and expenses, including legal
fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR
NEGLIGENCE, STRICT LIABILITY, BREACH OF WARRANTY OR
BREACH OF CONTRACT EXCEPT THOSE PROVIDED IN PARAGRAPH
1.F.3. YOU AGREE THAT THE FOUNDATION, THE TRADEMARK
OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL
NOT BE LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE OR INCIDENTAL DAMAGES EVEN IF
YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of receiving
it, you can receive a refund of the money (if any) you paid for it by
sending a written explanation to the person you received the work
from. If you received the work on a physical medium, you must
return the medium with your written explanation. The person or
entity that provided you with the defective work may elect to provide
a replacement copy in lieu of a refund. If you received the work
electronically, the person or entity providing it to you may choose to
give you a second opportunity to receive the work electronically in
lieu of a refund. If the second copy is also defective, you may
demand a refund in writing without further opportunities to fix the
problem.

1.F.4. Except for the limited right of replacement or refund set forth
in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of damages.
If any disclaimer or limitation set forth in this agreement violates the
law of the state applicable to this agreement, the agreement shall be
interpreted to make the maximum disclaimer or limitation permitted
by the applicable state law. The invalidity or unenforceability of any
provision of this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation,


the trademark owner, any agent or employee of the Foundation,
anyone providing copies of Project Gutenberg™ electronic works in
accordance with this agreement, and any volunteers associated with
the production, promotion and distribution of Project Gutenberg™
electronic works, harmless from all liability, costs and expenses,
including legal fees, that arise directly or indirectly from any of the
following which you do or cause to occur: (a) distribution of this or
any Project Gutenberg™ work, (b) alteration, modification, or
additions or deletions to any Project Gutenberg™ work, and (c) any
Defect you cause.

Section 2. Information about the Mission


of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new computers.
It exists because of the efforts of hundreds of volunteers and
donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project Gutenberg™’s
goals and ensuring that the Project Gutenberg™ collection will
remain freely available for generations to come. In 2001, the Project
Gutenberg Literary Archive Foundation was created to provide a
secure and permanent future for Project Gutenberg™ and future
generations. To learn more about the Project Gutenberg Literary
Archive Foundation and how your efforts and donations can help,
see Sections 3 and 4 and the Foundation information page at
www.gutenberg.org.

Section 3. Information about the Project


Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-profit
501(c)(3) educational corporation organized under the laws of the
state of Mississippi and granted tax exempt status by the Internal
Revenue Service. The Foundation’s EIN or federal tax identification
number is 64-6221541. Contributions to the Project Gutenberg
Literary Archive Foundation are tax deductible to the full extent
permitted by U.S. federal laws and your state’s laws.

The Foundation’s business office is located at 809 North 1500 West,


Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up
to date contact information can be found at the Foundation’s website
and official page at www.gutenberg.org/contact

Section 4. Information about Donations to


the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission of
increasing the number of public domain and licensed works that can
be freely distributed in machine-readable form accessible by the
widest array of equipment including outdated equipment. Many
small donations ($1 to $5,000) are particularly important to
maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws regulating


charities and charitable donations in all 50 states of the United
States. Compliance requirements are not uniform and it takes a
considerable effort, much paperwork and many fees to meet and
keep up with these requirements. We do not solicit donations in
locations where we have not received written confirmation of
compliance. To SEND DONATIONS or determine the status of
compliance for any particular state visit www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states where


we have not met the solicitation requirements, we know of no
prohibition against accepting unsolicited donations from donors in
such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot make


any statements concerning tax treatment of donations received from
outside the United States. U.S. laws alone swamp our small staff.

Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.

Section 5. General Information About


Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could be
freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose network of
volunteer support.
Project Gutenberg™ eBooks are often created from several printed
editions, all of which are confirmed as not protected by copyright in
the U.S. unless a copyright notice is included. Thus, we do not
necessarily keep eBooks in compliance with any particular paper
edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg Literary
Archive Foundation, how to help produce our new eBooks, and how
to subscribe to our email newsletter to hear about new eBooks.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like