WPF中程序中,很多人习惯了使用Button按钮的Click 事件添加一些命令处理代码,在处理小程序时倒也方便,但在多人团队中,显然违反了界面与代码分离的原则。
下面一步一步学习如何使用 Command 写界面与代码尽量分离的代码.
首先,创建一个简单窗口,有两个按钮和一个输出控件TextBox,用于定时向输出控件输出文本
<Window x:Class="WpfApp2.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:WpfApp2"
mc:Ignorable="d"
Title="MainWindow" Height="500" Width="800">
<Grid>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50" />
<RowDefinition />
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal">
<Button Margin="4" Width="120"
>继续</Button>
<Button Margin="4" Width="120"
>暂停</Button>
</StackPanel>
<TextBox x:Name="txtOut" Grid.Row="1"
AcceptsReturn="True"
TextWrapping="Wrap"
Margin="4"
IsReadOnly="True"
VerticalScrollBarVisibility="Auto"
>
</TextBox>
</Grid>
</Grid>
</Window>
第二步,给两个按钮添加 系统 默认的命令
<StackPanel Orientation="Horizontal">
<Button Margin="4" Width="120"
Command="MediaCommands.Play"
>继续</Button>
<Button Margin="4" Width="120"
Command="MediaCommands.Pause"
>暂停</Button>
</StackPanel>
第三步,添加这两个命令的实现代码
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
DispatcherTimer timer;
bool IsStar = false;
int myNum = 0;
private void Timer_Tick(object sender, EventArgs e)
{
if (IsStar)
{
if (txtOut.Text.Length > 10000)
txtOut.Text = "";
myNum++;
txtOut.AppendText(myNum + "\r\n");
txtOut.ScrollToEnd();
}
}
private void PlayCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
if (timer == null)
{
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(0.3);
timer.Tick += Timer_Tick;
timer.Start();
IsStar = true;
}
else
{
IsStar = true;
}
}
private void PlayCmdExecute(object target, CanExecuteRoutedEventArgs e)
{
e.CanExecute = timer == null || !IsStar;
}
private void PauseCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
IsStar = false;
}
private void PauseCmdExecute(object target, CanExecuteRoutedEventArgs e)
{
e.CanExecute = this.IsStar;
}
}
第4步,添加命令的执行绑定,在窗口的XAML 代码中添加以下代码
<Window.CommandBindings>
<CommandBinding Command="MediaCommands.Play"
Executed="PlayCmdExecuted"
CanExecute="PlayCmdExecute"/>
<CommandBinding Command="MediaCommands.Pause"
Executed="PauseCmdExecuted"
CanExecute="PauseCmdExecute"/>
</Window.CommandBindings>
这时候,命令的功能就完成了,程序可以正常运行
但为了使程序更完美,我们希望一下快捷键的功能,当用户在窗口中按下 Ctrl+P 开始播放功能,按下 Ctrl+B, 停止播放功能
第5步,添加快捷按键,在窗口的XAML 代码中添加以下代码
<Window.InputBindings>
<KeyBinding Key="P" Modifiers="Ctrl" Command="MediaCommands.Play" />
<KeyBinding Key="B" Modifiers="Ctrl" Command="MediaCommands.Pause" />
</Window.InputBindings>
再次运行程序,按下 Ctrl + P ,程序开始正常播放,完美