2012-05-26 41 views
3

我有这样的XAML:为什么我的WPF命令不能触发?

<UserControl x:Class="Foo.UserControls.Bar" 
      x:Name="FooBar" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 

    <StackPanel> 
     <WrapPanel Margin="4,0,0,0"> 
      <Button Command="{Binding Path=CreateCommand, ElementName=FooBar}"> 
       <TextBlock>Create</TextBlock> 
      </Button> 

这个代码隐藏(删除using S):

namespace Foo.UserControls 
{ 
    public partial class Bar : UserControl 
    { 
     public DelegateCommand CreateCommand { get; private set; } 

     public Bar() 
     { 
      InitializeComponent(); 

      CreateCommand = new DelegateCommand(Create); 
     } 

     private void Create(object action) 
     { 
      Console.WriteLine("foo"); 
     } 
    } 
} 

都与调试器和控制台日志记录,它似乎并没有以往任何时候都火。奇怪的是绑定似乎很好,因为它不会将任何错误记录到输出中。如果我故意破坏绑定,我会得到一个绑定错误,但通过上面的绑定,我不会收到任何错误,但它永远不会触发。

+0

尝试创建的命令后设置'的DataContext = this'在构造函数中。 – Gene

回答

7

尝试把CreateCommand = new DelegateCommand(Create);InitializeComponent();

+0

为什么这有帮助? – Default

+5

@Default控件在'InitializeComponent()'方法中创建它的绑定,并且此时CreateCommand未被分配。用户需要在'InitializeComponent()'之前移动赋值,或者在赋值命令后引发属性改变的事件。 –

相关问题