Lesson 38 - WPF - Menu and Dialog Controls
In the previous lesson, WPF - Data Displaying Controls, we went through WPF data displaying controls. In today's WPF tutorial, we're going to take a look at menus and dialogs.
Menu Controls
One of the other WPF controls are controls to create menus. Those controls are:
- Menu
- MenuItem
Menu
The Menu
control, together with the MenuItem
, is
used to create a collapsible menu, the application menu right below the window
title bar. This control can be in the form only once, and is created similarly
as TreeView
- by nesting MenuItem
controls into each
other.
The element structure in XAML has the <Menu>
tag at the
beginning, and of course ends with the </Menu>
tag. In
between them, the individual menu options are defined using the
<MenuItem>
tag. Those then have a handler method assigned. In
the header of each MenuItem
there's a text in which we can use
underscores to define the "hot key", which is a key shortcut. Individual options
can then be selected by pressing the Alt key together with the "hot
key" (the corresponding character on the keyboard). The header can even contain
e.g. a picture, a check box, etc. (see the MenuPreview
project).
Properties
Items
- the item collectionItemsSource
- the data source (we can assign an existing collection)Header
- header of the option (text, method reference,Image
, ...)
Events
Click
- the assigned method is called when the option is clicked
Example
XAML
<Menu BorderBrush="Black" Background="Transparent" FontFamily="Tahoma" Foreground="WhiteSmoke" FontSize="14"> <MenuItem Header="_File"> <MenuItem Header="_New file..." Click="NewFile" Foreground="Black"> <MenuItem.Icon> <Image Source="Img/new.png" Height="16" Width="16" /> </MenuItem.Icon> </MenuItem> . . . </Menu>
C#
The Click
event:
private void NewFile(object sender, RoutedEventArgs e) { MessageBox.Show("The New file option was selected"); }
Dialogs
The following dialogs are part of the predefined controls:
- MessageBox
- OpenFileDialog
- SaveFileDialog
MessageBox
This dialog can be used as an information or decision to control the application. In the dialog window we can ask, for example, if the selected item is to be deleted, and to run the appropriate methods when clicking Yes or No.
Properties
No important properties.
Methods
Show()
- Displays the dialog. This method returns the value of the selected option (of theMessageBoxResult
type). Various methods can then be called based on the return value. TheShow()
method has the following parameters:messageBoxText
- Any information, notification, or request. This text is required.caption
- The title of the dialog.
The Show()
method has several overloads, allowing us to specify
other parameters, such as:
MessageBoxButton
- displayed buttonsOK
OKCancel
YesNo
YesNoCancel
MessageBoxImage
- displayed icon of the dialogAsterisk
Error
Exclamation
Hand
Information
None
Question
Stop
Warning
MessageBoxResult
- the return valueCancel
No
None
OK
Yes
MessageBoxOptions
- sets the appearance of the dialog window. The following values are quite interesting:RightAlign
- the text of the dialog is aligned to the right sideRtlReading
- swaps positions of the dialog window controls. This means that the title is located on the right, the window close button and the entered text on the left, the selected icon on the right, and all the option buttons are reversed.
Example
Dialogs are opened only from C# code.
C#
private void Show(object sender, RoutedEventArgs e) { MessageBoxResult status = MessageBox.Show("Sample text.", "Title", MessageBoxButton.YesNoCancel, MessageBoxImage.Information, MessageBoxResult.Cancel); switch (status) { case MessageBoxResult.None: // sample code break; case MessageBoxResult.OK: // sample code break; case MessageBoxResult.Cancel: // sample code break; case MessageBoxResult.Yes: // sample code break; case MessageBoxResult.No: // sample code break; default: break; } }
OpenFileDialog
This dialog is the same as the Windows Explorer and is used to select a file.
Properties
The most important properties are:
FileName
- returns the name of the selected fileFilter
- filters the displayed files. The filter consists of the descriptive part and the corresponding file extension, separated by a vertical bar character|
(see the Example)InitialDirectory
- sets the initial directory the dialog should open
Example
C#
The following example shows how to load file contents into a
RichTextBox
. The control is named rtbxFile
:
private void DialogOpen(object sender, RoutedEventArgs e) { OpenFileDialog file = new OpenFileDialog(); soubor.Filter = "Text files (*.txt;*rtf)|*.txt;*rtf"; if (file.ShowDialog() == true) { rtbxFile.Document.Blocks.Clear(); FileStream fileStream = new FileStream(file.FileName, FileMode.Open); TextRange range = new TextRange(rtbxFile.Document.ContentStart,rtbxFile.Document.ContentEnd); FileInfo fi = new FileInfo(file.FileName); string suffix = fi.Extension.ToUpper(); if (suffix.Equals(".TXT")) { range.Load(fileStream, DataFormats.Text); } if (suffix.Equals(".RTF")) { range.Load(fileStream, DataFormats.Rtf); } if (!(suffix.Equals(".HTML") || suffix.Equals(".TXT"))) { MessageBox.Show("This file format is not supported.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning, MessageBoxResult.OK); } } else { MessageBox.Show("Cancel was clicked"); } }
SaveFileDialog
This dialog is also the same as the Windows Explorer and is used to save a file.
Properties
The most important properties are:
FileName
- the name of the selected fileFilter
- the filter for the displayed files. The filter consists of the descriptive part and the corresponding file extension again, separated by a vertical bar character|
(see Example)InitialDirectory
- sets the initial directory the dialog opens
Example
C#
The following example shows how to save text from a RichTextBox
into a file. The control is named rtbxFile
:
private void DialogSave(object sender, RoutedEventArgs e) { SaveFileDialog file = new SaveFileDialog(); file.Filter = "TXT file (*.txt)|*.txt|RTF file (*.rtf)|*.rtf"; if (file.ShowDialog() == true) { FileStream fileStream = new FileStream(file.FileName, FileMode.Create); TextRange range = new TextRange(rtbxFile.Document.ContentStart, rtbxFile.Document.ContentEnd); range.Save(fileStream, DataFormats.Text); } else { MessageBox.Show("Cancel was clicked"); } }
Note: An example of directory selection is also included in the project attached below.
In the next lesson, WPF - Container Controls, the container controls are waiting for us.
Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.
Download
By downloading the following file, you agree to the license terms
Downloaded 13x (2.71 MB)
Application includes source codes in language C#