为什么我的WPF命令没有触发?

4

我有这段XAML代码:

<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):

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");
        }
    }
}

无论使用调试器还是控制台日志记录,似乎都没有触发。奇怪的是,绑定似乎非常正常,因为它不会将任何错误记录到输出中。如果我故意破坏绑定,我会得到一个绑定错误,但是对于上述绑定,我没有收到任何错误信息,但它从未触发。


在创建命令后,尝试在构造函数中设置 DataContext = this - Gene
1个回答

9
尝试将CreateCommand = new DelegateCommand(Create);放在InitializeComponent();之前。

6
控件在InitializeComponent()方法中创建其绑定,此时CreateCommand未分配。用户需要将赋值移动到InitializeComponent()之前或在命令被分配后引发属性更改事件。 - Dan Busha

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接