码迷,mamicode.com
首页 > Windows程序 > 详细

WPF学习之路(五) 实例:写字板(续)

时间:2015-04-17 13:02:44      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

WordPad 2.0

上一期实现了一虽然建议但是功能比较全面的Wordpad程序,但是程序代码略显繁琐,这一期更新改进版。

 

MainWindows.xaml

添加 <Window.CommandBindings>节点,响应保存和关闭命令

<Window.CommandBindings>
        <CommandBinding Command="Close" Executed="CloseCommand" />
        <CommandBinding Command="Save" Executed="SaveCommand"  CanExecute="SaveCanExecute" />
</Window.CommandBindings>

Menu

 <MenuItem Header="File">
                <MenuItem Header="Copy" Command="Copy" />
                <MenuItem Header="Paste" Command="Paste" />
                <MenuItem Header="Cut" Command="Cut" />
                <Separator></Separator>
                <MenuItem Header="Save" Command="Save" />
                <MenuItem Header="Close" Command="Close" />
</MenuItem>

Tool 

<ToolBar Grid.Row="1">
            <Button Command="Copy">
                <Image Source="/Images/Copy16x16.png" />
             </Button>
            <Button Command="Paste">
                <Image Source="/Images/Paste16x16.png" />
            </Button>
            <Button Command="Cut">
                <Image Source="/Images/Cut16x16.png" />
            </Button>
            <Button Command="Save">
                <Image Source="/Images/Save16x16.png" />
            </Button>
            <Button Command="Close">
                <Image Source="/Images/Close16x16.png" />
            </Button>
</ToolBar>

TextBox

 <TextBox Grid.Row="2" AcceptsReturn="True" TextChanged="TextBox_TextChanged" />

MainWindow.xmal.cs

public partial class MainWindow : Window
{
    private bool isDirty = false;

    public MainWindow()
    {
        InitializeComponent();
    }

    private void CloseCommand(object sender, ExecutedRoutedEventArgs e)
    {
        MessageBox.Show("CloseCommand triggered with " + e.Source);
        App.Current.Shutdown();
    }

    private void SaveCommand(object sender, ExecutedRoutedEventArgs e)
    {
        MessageBox.Show("SaveCommand triggered with " + e.Source);
        isDirty = false;
    }

    private void SaveCanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = isDirty;
    }

    private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        isDirty = true;
    }
}

 

邮件菜单,快捷键,状态控制等功能已经全部实现

技术分享

 

 

解析

 所有功能都是通过Command来驱动的

用到的Command

ApplicationCommands.Save

ApplicationCommands.Paste

ApplicationCommands.Cut

ApplicationCommands.Save

ApplicationCommands.Close

 

TextBox直接支持前三种命令(WordPad1.0中原版使用的是TextBlock,不支持这三种命令,小编手滑,勿用了TextBox)

 

保存和关闭命令需要有响应的命令处理函数,首先设置Menu和ToolBar的Command属性,通过Command Binding关联Command和处理函数

执行Command时,会触发Execute事件。触发CanExecute事件时,事件处理函数需要返回CanExecute属性,告知系统是否可用

 

 

 

 

 

 

 

 

 

 

 

 

To be continue...

WPF学习之路(五) 实例:写字板(续)

标签:

原文地址:http://www.cnblogs.com/alex09/p/4433975.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!