-
- 是WPF中的一些控件确有自己的命令绑定。最简单的例子就是TextBox控件,它有自己的Cut、 Copy和Paste命令的内建绑定,这些命令可以与剪贴板交互,还有Undo和Redo命令的内建绑定。
- 下面的XAML展示了这些内建命令绑定的力量:
3.4.3 带有内建命令绑定的控件
<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Orientation="Horizontal"
Height="25">
<Button Command="Cut"
CommandTarget="{Binding ElementName=textBox}"
Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}" />
<Button Command="Copy"
CommandTarget="{Binding ElementName=textBox}"
Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}" />
<Button Command="Paste"
CommandTarget="{Binding ElementName=textBox}"
Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}" />
<Button Command="Undo"
CommandTarget="{Binding ElementName=textBox}"
Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}" />
<Button Command="Redo"
CommandTarget="{Binding ElementName=textBox}"
Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}" />
<TextBox x:Name="textBox" Width="1000" />
</StackPanel>
其中:
Command="Cut":表示让命令"Cut"与Button关联
CommandTarget="{Binding ElementName=textBox}":指定引发命令的元素为textBox。也就是在是从textBox执行命令,而不是从Button执行。
Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}":指定Button的Content属性为命令的Text值
这个例子说明:虽然Button和TextBox可以实现很多的交互,但它们互相并不了解,这也说明WPF的内建命令如此重要。