分类目录: WPF
Command
Post date:
Author: goddenty
Number of comments: no comments
ICommand:
bool CanExcecute: 表示命令是否可以执行
Execute(object):执行命令,并输入object参数
CanExecuteChanged:
ICommandSource:
Command, CommandParameter, CommandTarget
CommandBinding
定义和关联Command的具体实现
<Window.CommandBindings>
<CommandBinding Command="Application.Open"
Executed="OpenCmdExecuted"
CanExecute="OpenCmdCanExecute" />
</Window.CommandBindings>
Routed Command
当调用CanExeucte方法时,分别会产生CanExecute和PreviewCanExecute
当调用Execute方法时,会产生Executed和PreviewExecuted
Command Repository
WPF中内置的命令包括:
ApplicationCommands, NavigationCommands, MediaCommands, EditingCommands, ComponentCommands
<Window>
<Window.CommandBindings>
<CommandBinding Command="Help" CanExecute="HelpCanExecute"
Executed="HelpExecuted" />
</Window.CommandBindings>
<Window.InputBindings>
<KeyBinding Command="Help" Key="H" Modifiers="Ctrl"/>
<MouseBinding Command="Help" MouseAction="LeftDoubleClick"/>
</Window.InputBindings>
<StackPanel>
<Button Command="Help" Content="帮助"/>
</StackPanel>
</Window>
private void HelpCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute=true;
e.Handle=true;
}
InputBindings
可以将鼠标或者键盘的事件和Command关联起来。
<Label Style="{StaticResource FS_Label}" HorizontalContentAlignment="Left" FontSize="14" Content="{Binding ItemName}" Width="{Binding Path=ActualWidth, ElementName=deviceStatusListBox}" Background="Transparent">
<Label.InputBindings>
<MouseBinding MouseAction="LeftDoubleClick" Command="{Binding DataContext.MenuItemDoubleClickCommand, UpdateSourceTrigger=PropertyChanged, ElementName=deviceStatusListBox}" CommandParameter="{Binding Path=SelectedItem, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}"/>
</Label.InputBindings>
</Label>
Command Parameter:
Parameter的值是支持绑定的,也可以是普通的值
<Button Command="NavigationCommands.Zoom"
CommandParameter="{Binding ElementName=txtZoom, Path=Text}">
Zoom To Value
</Button>
UI event to command:
需要使用到Prism的框架。
<Window ...
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
xmlns:prism="http://prismlibrary.com/">
<ListBox Grid.Row="1" Margin="5" ItemsSource="{Binding Items}" SelectionMode="Single">
<i:Interaction.Triggers>
<!-- This event trigger will execute the action when the corresponding event is raised by the ListBox. -->
<i:EventTrigger EventName="SelectionChanged">
<!-- This action will invoke the selected command in the view model and pass the parameters of the event to it. -->
<prism:InvokeCommandAction Command="{Binding SelectedCommand}" TriggerParameterPath="AddedItems" />
</i:EventTrigger>
</i:Interaction.Triggers>
</ListBox>
</Window>