<Window x:Class="CommandParematerDemo.MainWindow"
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:CommandParematerDemo"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="26"></RowDefinition>
<RowDefinition Height="26"></RowDefinition>
<RowDefinition Height="26"></RowDefinition>
<RowDefinition Height="100"></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Text="name:" HorizontalAlignment="Left"></TextBlock>
<TextBox Name="nameTextBox" Margin="60,0,0,0"></TextBox>
<Button Name="tButton" Content="new teacher" Grid.Row="1" Command="New" CommandParameter="Teacher"></Button>
<Button Name="sButton" Content="new student" Grid.Row="2" Command="New" CommandParameter="Student"></Button>
<ListView Name="aListView" Grid.Row="3"></ListView>
</Grid>
</Grid>
<Window.CommandBindings>
<CommandBinding Command="New" CanExecute="New_canExecute" Executed="New_execute"></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.Navigation;
using System.Windows.Shapes;
namespace CommandParematerDemo
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
void New_canExecute(object sender, CanExecuteRoutedEventArgs e) {
if (string.IsNullOrEmpty(nameTextBox.Text))
{
e.CanExecute = false;
}
else {
e.CanExecute = true;
}
}
void New_execute(Object sender, ExecutedRoutedEventArgs e) {
string name = nameTextBox.Text;
if (e.Parameter.ToString() == "Student")
{
aListView.Items.Add(string.Format($"New student:{name}"));
}
else {
aListView.Items.Add(string.Format($"New Teacher:{name}"));
}
}
}
}
界面上有两个按钮,一个用于新建teacher,一个用于新建student,都使用new命令,那么就是通过CommandParameter来区分,命令源一定是实现了ICommandResource接口的对象,而ICommandSource有一个属性就是CommandPrameter。
网友评论