自定义了一个MyCanvas类,在其中注册了一个CommandBinding,其功能是自动添加一个TextBox控件到MyCanvas,
1 public class MyCanvas : Canvas 2 { 3 public MyCanvas() 4 { 5 CommandManager.RegisterClassCommandBinding(typeof(MyCanvas), new CommandBinding(ApplicationCommands.New, MyExecuted)); 6 } 7 8 private void MyExecuted(object sender, ExecutedRoutedEventArgs e) 9 { 10 TextBox txt = new TextBox{ Width = 60, Height = 20 ,Text = "AAA"}; 11 txt.Margin = new Thickness(10); 12 this.Children.Add(txt); 13 } 14 15 }
在界面上,一个MyCanvas套着另一个MyCanvas,一个Button的命令目标指定为子MyCanvas,界面代码:
<Window> <local:MyCanvas x:Name="canvas1" Background="LightBlue" > <local:MyCanvas x:Name="canvas2" Background="Wheat" Width="200" Height="100" Margin="70" /> <Button Name="btn2" Content="增加Canvas2子控件" Command="New" CommandTarget="{Binding ElementName=canvas2}" Canvas.Left="246" Canvas.Top="228" /> </local:MyCanvas> </Window>
单击btn2激发命令后,按理说canvas2应该先接收到这个命令,创建和添加TextBox控件到canvas2 (查看MyExecuted事件处理程序的 sender、e.Soure、e.OriginalSource,都是canvas2.),然而实际结果却是canvas1执行了命令,这是什么原因?
执行结果:
this.Children.Add(txt);
改成这样
((MyCanvas)sender).Children.Add(txt);
为什么canvas2不执行命令?
@seewold: 命令是canvas2触发的,不然sender咋么会是canvas2,但this是指向canvas1的