Tải bản đầy đủ - 0 (trang)
17-13. Support Application Commands in a User Control

17-13. Support Application Commands in a User Control

Tải bản đầy đủ - 0trang

CHAPTER 17 ■ WINDOWS PRESENTATION FOUNDATION



Solution

Use the System.Windows.Input.CommandManager to register an instance of the System.Windows.Input.

CommandBinding class for each member of System.Windows.Input.ApplicationCommands that you need to

support in your user control. The CommandBinding specifies the type of command you want to receive

notification of, specifies a CanExecute event handler to determine when the command can be executed,

and specifies an Executed event handler to be called when the command is executed.



How It Works

There are many predefined commands in WPF to support common scenarios. These commands are

grouped as static properties on five different classes, mostly in the System.Windows.Input namespace, as

shown in Table 17-4.

Table 17-4. Predefined Common Commands



Value



Description



ApplicationCommands



Common commands for an application; for example, Copy, Paste, Undo, Redo,

Find, Open, SaveAs, and Print



ComponentCommands



Common commands for user interface components; for example, MoveLeft,

MoveToEnd, and ScrollPageDown



MediaCommands



Common commands used for multimedia; for example, Play, Pause, NextTrack,

IncreaseVolume, and ToggleMicrophoneOnOff



NavigationCommands



A set of commands used for page navigation; for example, BrowseBack, GoToPage,

NextPage, Refresh, and Zoom



EditingCommands



A set of commands for editing documents; for example, AlignCenter,

IncreaseFontSize, EnterParagraphBreak, and ToggleBold



Each command has a System.Windows.Input.InputGestureCollection that specifies the possible

mouse or keyboard combinations that trigger the command. These are defined by the command itself,

which is why you are able to register to receive these automatically by registering a CommandBinding for a

particular command.

A CommandBinding for a particular command registers the CanExecute and Executed handlers so that

the execution and the validation of the execution of the command are routed to these event handlers.



The Code

The following example creates a UserControl called FileInputControl that can be used to browse to a file

using Microsoft.Win32.OpenFileDialog and display the file name in a System.Windows.Controls.TextBox.



823



www.it-ebooks.info



CHAPTER 17 ■ WINDOWS PRESENTATION FOUNDATION



It registers a CommandBinding for two application commands, Open and Find. When the user control

has focus and the keyboard shortcuts for the Open and Find commands (Ctrl+O and Ctrl+F, respectively)

are used, the Executed event handler for the respective command is invoked.

The Executed event handler for the Find command launches the OpenFileDialog, as if the user has

clicked the Browse button. This command can always be executed, so the CanExecute event handler

simply sets the CanExecute property of System.Windows.Input.CanExecuteRoutedEventArgs to True.

The Executed event handler for the Open command launches the file that is currently displayed in the

TextBox. Therefore, the CanExecute event handler for this command sets the CanExecuteRoutedEventArgs

to True only if there is a valid FileName. The XAML for the FileInputControl is as follows:


xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">











The code-behind for the FileInputControl is as follows:

using

using

using

using

using



System.Diagnostics;

System.IO;

System.Windows.Controls;

System.Windows.Input;

Microsoft.Win32;



namespace Apress.VisualCSharpRecipes.Chapter17

{

public partial class FileInputControl : UserControl

{

public FileInputControl()

{

InitializeComponent();

// Register command bindings

// ApplicationCommands.Find

CommandManager.RegisterClassCommandBinding(

typeof(FileInputControl),

new CommandBinding(

ApplicationCommands.Find,

FindCommand_Executed,

FindCommand_CanExecute));

// ApplicationCommands.Open

CommandManager.RegisterClassCommandBinding(

typeof(FileInputControl),

new CommandBinding(



824



www.it-ebooks.info



CHAPTER 17 ■ WINDOWS PRESENTATION FOUNDATION



ApplicationCommands.Open,

OpenCommand_Executed,

OpenCommand_CanExecute));

}

#region Find Command

private void FindCommand_CanExecute(

object sender,

CanExecuteRoutedEventArgs e)

{

e.CanExecute = true;

}

private void FindCommand_Executed(

object sender,

ExecutedRoutedEventArgs e)

{

DoFindFile();

}

#endregion

#region Open Command

private void OpenCommand_CanExecute(

object sender,

CanExecuteRoutedEventArgs e)

{

e.CanExecute =

!string.IsNullOrEmpty(this.FileName)

&& File.Exists(this.FileName);

}

private void OpenCommand_Executed(

object sender,

ExecutedRoutedEventArgs e)

{

Process.Start(this.FileName);

}

#endregion

private void BrowseButton_Click(

object sender,

System.Windows.RoutedEventArgs e)

{

DoFindFile();

}



825



www.it-ebooks.info



CHAPTER 17 ■ WINDOWS PRESENTATION FOUNDATION



private void DoFindFile()

{

OpenFileDialog dlg = new OpenFileDialog();

if(dlg.ShowDialog() == true)

{

this.FileName = dlg.FileName;

}

}

public string FileName

{

get

{

return txtBox.Text;

}

set

{

txtBox.Text = value;

}

}

}

}

The following XAML shows how to use the FileInputControl in a window. If the TextBox has the

focus, then pressing the keyboard shortcut Ctrl+F will automatically open the OpenFileDialog. If a file is

selected and a valid file name appears in the TextBox, then the shortcut Ctrl+O will launch it.


xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:local="clr-namespace:Apress.VisualCSharpRecipes.Chapter17;assembly="

Title="Recipe17_13" Height="80" Width="300">











17-14. Create a Lookless Custom Control

Problem

You need to create a custom control that encapsulates functionality and behavior logic but can have its

visual appearance changed by consumers. For example, you need consumers to be able to change the

style, template, or visual theme of your control for a particular context, application, or operating system

theme.



826



www.it-ebooks.info



CHAPTER 17 ■ WINDOWS PRESENTATION FOUNDATION



Solution

Create a lookless custom control class that contains interaction and behavior logic but little or no

assumptions about its visual implementation. Then declare the default visual elements for it in a control

template within a default style.



■ Tip When creating the code for a custom control, you need to ensure it is lookless and assumes as little as

possible about the actual implementation of the visual elements in the control template, because it could be

different across different consumers. This means ensuring that the UI is decoupled from the interaction logic by

using commands and bindings, avoiding event handlers, and referencing elements in the ControlTemplate

whenever possible.



How It Works

The first step in creating a lookless custom control is choosing which control to inherit from. You could

derive from the most basic option available to you, because it provides the minimum required

functionality and gives the control consumer the maximum freedom. On the other hand, it also makes

sense to leverage as much built-in support as possible by deriving from an existing WPF control if it

possesses similar behavior and functionality to your custom control. For example, if your control will be

clickable, then it might make sense to inherit from the Button class. If your control is not only clickable

but also has the notion of being in a selected or unselected state, then it might make sense to inherit

from ToggleButton.

Some of the most common base classes you will derive from are listed in Table 17-5.

Table 17-5. Common Base Classes for Creating a Custom Control



Name



Description



FrameworkElement



This is usually the most basic element from which you will derive. Use this when

you need to draw your own element by overriding the OnRender method and

explicitly defining the component visuals. FrameworkElement classes tend not to

interact with the user; for example, the WPF Image and Border controls are

FrameworkElement classes.



Control



Control is the base class used by most of the existing WPF controls. It allows you to

define its appearance by using control templates, and it adds properties for setting

the background and foreground, font, padding, tab index, and alignment of content.

It also supports double-clicking through the MouseDoubleClick and

PreviewMouseDoubleClick events.



827



www.it-ebooks.info



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

17-13. Support Application Commands in a User Control

Tải bản đầy đủ ngay(0 tr)

×