<Window x:Class="WpfApplication1.Window29"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window29" Height="278" Width="398">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="24" />
<RowDefinition Height="4" />
<RowDefinition Height="24" />
<RowDefinition Height="4" />
<RowDefinition Height="24" />
<RowDefinition Height="4" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<!--命令和命令参数-->
<TextBlock HorizontalAlignment="Left" Name="textBlock1" Text="Name:" VerticalAlignment="Center" Grid.Row="0"/>
<TextBox x:Name="txtName" Margin="60,0,0,0" Grid.Row="0"></TextBox>
<Button Content="New Teacher" Grid.Row="2" Command="New" CommandParameter="Teacher"></Button>
<Button Content="New Student" Grid.Row="4" Command="New" CommandParameter="Student"></Button>
<ListBox Grid.Row="6" x:Name="lbInfos">
</ListBox>
</Grid>
<!--为窗体添加CommandBinding-->
<Window.CommandBindings>
<CommandBinding Command="New" CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed">
</CommandBinding>
</Window.CommandBindings>
</Window>
----------------------------------------------------------------------------------------------------------------------------------------
public partial class Window29 : Window
{
public Window29()
{
InitializeComponent();
}
private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (string.IsNullOrEmpty(txtName.Text))
{
e.CanExecute = false;
}
else
{
e.CanExecute = true;
}
//路由终止,提高系统性能
e.Handled = true;
}
private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
if (e.Parameter.ToString() == "Student")
{
this.lbInfos.Items.Add(string.Format("New Student:{0} 好好学习,天天向上。",txtName.Text));
}
else if(e.Parameter.ToString()=="Teacher")
{
this.lbInfos.Items.Add(string.Format("New Teacher:{0} 学而不厌,诲人不倦。", txtName.Text));
}
//路由终止,提高系统性能
e.Handled = true;
}
}