<Window x:Class="WpfDemo.CommandParameter" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfDemo" mc:Ignorable="d" Title="CommandParameter" Height="300" Width="300"> <Grid> <Grid HorizontalAlignment="Right" Height="239" Margin="0,10,10,0" VerticalAlignment="Top" Width="272"> <Grid.RowDefinitions> <RowDefinition Height="40*"></RowDefinition> <RowDefinition Height="7"></RowDefinition> <RowDefinition Height="21*"></RowDefinition> <RowDefinition Height="7"></RowDefinition> <RowDefinition Height="21*"></RowDefinition> <RowDefinition Height="7"></RowDefinition> <RowDefinition Height="133*"/> </Grid.RowDefinitions> <Label x:Name="label" Content="Name" VerticalContentAlignment="Center" VerticalAlignment="Center" HorizontalAlignment="Left" Grid.Row="0" Height="36" Width="50" Margin="0,2"/> <TextBox x:Name="textBox" Grid.Row="0" Height="22" Margin="64,8,25,0" VerticalAlignment="Top"/> <Button Grid.Row="2" Content="NEW Teacher" Command="New" CommandParameter="Teacher" CommandTarget="{Binding ElementName=textBox}"/> <Button Grid.Row="4" Content="NEW Student" Command="New" CommandParameter="Student" CommandTarget="{Binding ElementName=textBox}"/> <ListBox x:Name="listBox" Grid.Row="6" /> </Grid> </Grid> <Window.CommandBindings> <CommandBinding Command="New" CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed"></CommandBinding> </Window.CommandBindings> </Window>
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace WpfDemo { /// <summary> /// CommandParameter.xaml 的互動邏輯 /// </summary> public partial class CommandParameter : Window { public CommandParameter() { InitializeComponent(); } private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e) { if(e.OriginalSource is TextBox) { TextBox t = e.OriginalSource as TextBox; if(string.IsNullOrEmpty(t.Text)) { e.CanExecute = false; } else { e.CanExecute = true; } }else { e.CanExecute = false; } } private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) { if (e.OriginalSource is TextBox) { TextBox t = e.OriginalSource as TextBox; if(e.Parameter.ToString()=="Teacher") { this.listBox.Items.Add("Teacher:"+t.Text); } if (e.Parameter.ToString() == "Student") { this.listBox.Items.Add("Student:" + t.Text); } } } } }