Dec
14
Written by:
Steve Gray
12/14/2010 7:54 AM
This is a code example for a WPF RoutedCommand. It’s a complete example, just copy the code into a Visual Studio WPF Application project and it should run
Here is the XAML for the form
Code Snippet
- <Window x:Class="Window1"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:custom="clr-namespace:WpfApplication1"
-
- Title="Window1" Height="300" Width="300">
- <Window.CommandBindings>
- <CommandBinding Command="{x:Static custom:Window1.AddSugar}"
- Executed="ExecutedAddSugar"
- CanExecute="CanExecuteAddSugar" />
- </Window.CommandBindings>
-
-
- <Grid>
- <Menu Margin="0,0,0,234">
- <MenuItem
- Header="File"
- Name="mnuFile" />
- <MenuItem
- Header="Add Sugar"
- Name="mnuAddSugar"
- Command="{x:Static custom:Window1.AddSugar}" />
- </Menu>
-
- <Button
- Content="Add Sugar"
- Command="{x:Static custom:Window1.AddSugar}"
- Height="26"
- HorizontalAlignment="Left"
- Margin="24,47,0,0"
- Name="Button1"
- VerticalAlignment="Top"
- Width="130" />
- </Grid>
- </Window>
Here is the code behind for the form:
Code Snippet
- Public Class Window1
-
-
- Public Shared Property AddSugar As New RoutedCommand
-
- Private Sub ExecutedAddSugar(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs)
- MessageBox.Show("Custom Command Executed")
- End Sub
-
- ' CanExecuteRoutedEventHandler that only returns true if
- ' the source is a control.
- Private Sub CanExecuteAddSugar(ByVal sender As Object, ByVal e As CanExecuteRoutedEventArgs)
- Dim target As Control = TryCast(e.Source, Control)
-
- If target IsNot Nothing Then
- e.CanExecute = True
- Else
- e.CanExecute = False
- End If
- End Sub
-
-
- End Class
As always, I welcome your comments!