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

标签 c# wpf mvvm

我有这个 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");
        }
    }
}

无论是使用调试器还是控制台日志记录,它似乎都不会触发。奇怪的是绑定(bind)似乎很好,因为它没有将任何错误记录到输出中。如果我故意破坏绑定(bind),我确实会收到绑定(bind)错误,但使用上述绑定(bind)我不会收到任何错误,但它永远不会触发。

最佳答案

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

关于c# - 为什么我的 WPF 命令没有触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10767583/

相关文章:

c# - 如何在计算模拟器中同时调试多个 Azure 角色?

c# - 单击按钮时调用 _Paint

c# - 环绕面板 : Trying to make the ItemWidth equal to the max width of any one element

c# - 当 child 有错误时使 UserControl parent 无效

c# - 如何在不阻塞 UI 的情况下顺序运行多个任务?

c# - 如何将 WPF 控件文本绑定(bind)到 bool 值,并在 xaml 中决定文本

WPF 下划线绑定(bind) (MVVM)

c# - WPF MVVM : Update label depending on Textbox input (2nd Attempt)

c# - 从 linq 查询中获取值(value)(需要想法/建议)

c# - asp.net 在一个类中处理