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

潜移默化学会WPF--Command(命令)学习(二) - AYUI框架 - 博客园

时间:2019-03-01 22:19:28      阅读:281      评论:0      收藏:0      [点我收藏+]

标签:document   hide   spl   extc   body   too   item   lap   表示   

原文:潜移默化学会WPF--Command(命令)学习(二) - AYUI框架 - 博客园

2. 基本功

   2.1 先看一段代码

技术图片
技术图片
 1 <Window x:Class="Commands.SimpleDocument"
2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4 Title="SimpleDocument" Height="300" Width="300"
5 >
6 <Grid>
7 <Grid.RowDefinitions>
8 <RowDefinition Height="Auto"></RowDefinition>
9 <RowDefinition Height="Auto"></RowDefinition>
10 <RowDefinition></RowDefinition>
11 </Grid.RowDefinitions>
12 <Menu Grid.Row="0">
13 <MenuItem Header="File">
14 <MenuItem Command="New"></MenuItem>
15 <MenuItem Command="Open"></MenuItem>
16 <MenuItem Command="Save"></MenuItem>
17 <MenuItem Command="SaveAs"></MenuItem>
18 <Separator></Separator>
19 <MenuItem Command="Close"></MenuItem>
20 </MenuItem>
21 </Menu>
22
23 <ToolBarTray Grid.Row="1">
24 <ToolBar>
25 <Button Command="New">New</Button>
26 <Button Command="Open">Open</Button>
27 <Button Command="Save">Save</Button>
28 </ToolBar>
29 <ToolBar>
30 <Button Command="Cut">Cut</Button>
31 <Button Command="Copy">Copy</Button>
32 <Button Command="Paste">Paste</Button>
33
34 </ToolBar>
35 </ToolBarTray>
36 <TextBox Name="txt" Margin="5" Grid.Row="2"
37 TextWrapping="Wrap" AcceptsReturn="True"
38 TextChanged="txt_TextChanged"></TextBox>
39 </Grid>
40 </Window>
技术图片

当命令是系统定义的Command后面的值中的 ApplicationCommands可以不写,直接写后面的值

前台能定义的,后台也能用代码定义好,这点要坚信

例如

 CommandBinding binding= new CommandBinding(ApplicationCommands.Save);

 binding.Executed += SaveCommand_Executed;

 binding.CanExecute += SaveCommand_CanExecute;
 this.CommandBindings.Add(binding);

 

类似等同于

 <Window.Resources>

<CommandBinding x:Key="binding" Command="ApplicationCommands.Save"
Executed="SaveCommand" CanExecute="SaveCommand_CanExecute" />

 </Window.Resources>

备注:如果不写Key,所有的调了save命令的对象都执行 Executed定义好的方法, CanExecute表示是否执行 Executed定义好的方法,例如在后台代码中 SaveCommand_CanExecute这个方法中写 e.CanExecute=true,表示 SaveCommand这个方法,当触发时可以执行,设false就不可以执行了,这点类似于 控件的IsEnabled属性,能用不能用,IsEnabled=false;此按钮单击也没效果了,e.CanExecute=false跟那个一个道理

然后这样调用

<TextBox Margin="5" Grid.Row="2"  TextWrapping="Wrap" AcceptsReturn="True" >

<TextBox.CommandBindings>
    <StaticResource ResourceKey="binding"></StaticResource>
</TextBox.CommandBindings>
</TextBox>

备注:AcceptsReturn=true表示此文本框可以 按回车键换行

 

下一章讲 自定义命令

潜移默化学会WPF--Command(命令)学习(二) - AYUI框架 - 博客园

标签:document   hide   spl   extc   body   too   item   lap   表示   

原文地址:https://www.cnblogs.com/lonelyxmas/p/10459040.html

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