WPF学习系列030: 3.4.1 内建命令

 

  •  
    1. 命令是任何一个实现了ICommand接口(位于System.Windows.Input命名空间)的对象,每个对象定义了3个简单的成员:
      1. Execute:执行特定命令的逻辑的方法。
      2. CanExecute:如果命令允许被执行,则该方法返回true;如果不允许执行,则返回false
      3. CanExecuteChanged——无论何时,只要CanExecute的值改变,该事件就会触发。
    1. 创建自定义命令例子
    1. WPF5个类的静态属性实现了WPF的内建命令:
      1. ApplicationCommands
    1. ComponentCommands
    1. MediaCommands
    1. NavigationCommands
    1. EditingCommands
    1. 内建命令使用的流程
      1. 将元素的Command特性设置为内建命令
    1. 向元素或父元素添加CommandBinding对象。
    1. 内建命令的Text字符串是由每个RoutedUICommand定义的,WPF会自动对Text作本地化,并把它转换为任何一种WPF支持的语言
    2. 内建命令使用示例
  • 3.4.1  内建命令

    XAML文件

    <Window x:Class="Custom_RoutedCommand.MainWindow"

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

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

            xmlns:custom="clr-namespace:Custom_RoutedCommand"

            Title="Custom RoutedCommand Sample"

            Name="RootWindow"

            Height="500"

            Width="600"

            Focusable="True">

        <Window.CommandBindings>

            <CommandBinding Command="{x:Static custom:MainWindow.ColorCmd}"

                            Executed="ColorCmdExecuted"

                            CanExecute="ColorCmdCanExecute" />

        </Window.CommandBindings>

        <DockPanel>

            <Menu DockPanel.Dock="Top"

                  Height="25">

                <MenuItem Header="Commands">

                    <MenuItem Header="Color Command"

                              Command="{x:Static custom:MainWindow.ColorCmd}" />

                </MenuItem>

            </Menu>

            <Border BorderBrush="Black"

                    BorderThickness="1"

                    Margin="10"

                    Height="175"

                    Width="375"

                    DockPanel.Dock="Top">

                <TextBlock TextWrapping="Wrap"

                           Margin="3">

                    The Color Command chages the background color of a StackPanel.

                    <LineBreak />

                    <LineBreak />

                    In order for the command attached to the MenuItem to be enabled, the

                    StackPanel must have keyboard focus.  Use the TAB key to change focus.

                    <LineBreak />

                    <LineBreak />

                    Since the command attached to the Button has the CommandTarget

                    set to the first StackPanel, the StackPanel does not need focus.

                    <LineBreak />

                </TextBlock>

            </Border>

            <StackPanel Orientation="Horizontal"

                        HorizontalAlignment="Center"

                        DockPanel.Dock="Bottom">

                <Border BorderBrush="Black"

                        BorderThickness="1"

                        Margin="10"

                        Height="200"

                        Width="200">

                    <StackPanel Name="FirstStackPanel"

                                Background="AliceBlue"

                                Focusable="True">

                        <StackPanel.CommandBindings>

                            <CommandBinding Command="{x:Static custom:MainWindow.ColorCmd}"

                                            Executed="ColorCmdExecuted"

                                            CanExecute="ColorCmdCanExecute" />

                        </StackPanel.CommandBindings>

                        <Label>First StackPanel</Label>

     

                        <Button Command="{x:Static custom:MainWindow.ColorCmd}"

                                CommandParameter="ButtonOne"

                                CommandTarget="{Binding ElementName=FirstStackPanel}"

                                Content="CommandTarget = FirstStackPanel" />

                    </StackPanel>

                </Border>

                <Border BorderBrush="Black"

                        BorderThickness="1"

                        Margin="10"

                        Height="200"

                        Width="200">

                    <StackPanel Background="AliceBlue"

                                Focusable="True">

                        <Label>Second StackPanel</Label>

                    </StackPanel>

                </Border>

            </StackPanel>

        </DockPanel>

    </Window>

    对应的代码隐藏文件

    using System.Windows;

    using System.Windows.Controls;

    using System.Windows.Input;

    using System.Windows.Media;

     

    namespace Custom_RoutedCommand

    {

        /// <summary>

        /// Interaction logic for MainWindow.xaml

        /// </summary>

        public partial class MainWindow : Window

        {

            public static RoutedCommand ColorCmd = new RoutedCommand();

            public MainWindow()

            {

                InitializeComponent();

            }

            // ExecutedRoutedEventHandler for the custom color command.

            private void ColorCmdExecuted(object sender, ExecutedRoutedEventArgs e)

            {

                Panel target = e.Source as Panel;

                if (target != null)

                {

                    if (target.Background == Brushes.AliceBlue)

                    {

                        target.Background = Brushes.LemonChiffon;

                    }

                    else

                    {

                        target.Background = Brushes.AliceBlue;

                    }

                }

            }

     

            // CanExecuteRoutedEventHandler for the custom color command.

            private void ColorCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)

            {

                if (e.Source is Panel)

                {

                    e.CanExecute = true;

                }

                else

                {

                    e.CanExecute = false;

                }

            }

        }

    }

    CloseCopyCutDeleteFindHelpNewOpenPastePrintPrintPreviewPropertiesRedoReplaceSaveSaveAsSelectAllStopUndo

    MoveDownMoveLeftMoveRightMoveUpScrollByLineScrollPageDownScrollPageLeftScrollPageRightScrollPageUpSelectToEndSelectToHomeSelectToPageDownSelectToPageUp

    ChannelDownChannelUpDecreaseVolumeFastForwardIncreaseVolumeMuteVolumeNextTrackPausePlayPreviousTrackRecordRewindSelectStop

    BrowseBackBrowseForwardBrowseHomeBrowseStopFavoritesFirstPageGoToPageLastPageNextPagePreviousPageRefreshSearchZoom

    AlignCenterAlignJustifyAlignLeftAlignRightCorrectSpellingErrorDecreaseFontSizeDecreaseIndentationEnterLineBreakEnterParagraphBreakIgnoreSpellingErrorIncreaseFontSizeIncreaseIndentationMoveDownByLineMoveDownByPageMoveDownByParagraphMoveLeftByCharacterMoveLeftByWordMoveRightByCharacterMoveRightByWord

    每个属性并不会返回实现ICommand的独特类型,相反,它们都是RoutedUICommand的实例。RoutedUICommand类不仅实现了ICommand接口,还可以像路由事件一样支持冒泡。

    例如:

    helpButton.Command = ApplicationCommands.Help;

    例如:

    this.CommandBings.Add(new CommandBinding(ApplicationCommands.Help, this.HelpExecuted, this.HelpCanExecute));

    其中:ApplicationCommands.Help 是内建命令

    this.HelpExecuted 是自定义执行命令的内容方法

    this.HelpCanExecute 是自定义命令是否可执行的方法

    XAML文件

    <Window x:Class="WpfApplication1.AboutDialog"

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

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

            Title="About WPF Unleashed"

            SizeToContent="WidthAndHeight"

            Background="OrangeRed">

        <Window.CommandBindings>

            <CommandBinding Command="Help"

                            CanExecute="HelpCanExecute"

                            Executed="HelpExecuted" />

        </Window.CommandBindings>

        <StackPanel>

            <Label FontWeight="Bold"

                   FontSize="20"

                   Foreground="White">

                WPF Unleashed (Version 3.0)

            </Label>

            <Label>

                © 2006 SAMS Publishing

            </Label>

            <Label>

                Installed Chapters:

            </Label>

            <ListBox>

                <ListBoxItem>

                    Chapter 1

                </ListBoxItem>

                <ListBoxItem>

                    Chapter 2

                </ListBoxItem>

            </ListBox>

            <StackPanel Orientation="Horizontal"

                        HorizontalAlignment="Center">

                <Button MinWidth="75"

                        Margin="10"

                        Command="Help"

                        Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}" />

                <Button MinWidth="75"

                        Margin="10">

                    OK

                </Button>

            </StackPanel>

            <StatusBar>

                You have successfully registered this product.

            </StatusBar>

        </StackPanel>

    </Window>

    对应的代码隐藏文件

    using System.Windows;

    using System.Windows.Input;

     

    namespace WpfApplication1

    {

        /// <summary>

        /// MainWindow.xaml 的交互逻辑

        /// </summary>

        public partial class AboutDialog : Window

        {

            public AboutDialog()

            {

                InitializeComponent();

            }

     

            private void HelpCanExecute(object sender, CanExecuteRoutedEventArgs e)

            {

                e.CanExecute = true;

            }

     

            private void HelpExecuted(object sender, ExecutedRoutedEventArgs e)

            {

                System.Diagnostics.Process.Start("http://www.adamnathan.net/wpf");

            }

        }

    }

     

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值