Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/261.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么我的WPF命令没有开火?_C#_Wpf_Mvvm - Fatal编程技术网

C# 为什么我的WPF命令没有开火?

C# 为什么我的WPF命令没有开火?,c#,wpf,mvvm,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"> <Stac

我有这个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>

通过调试器和控制台日志记录,它似乎永远不会启动。奇怪的是,绑定似乎很好,因为它不会将任何错误记录到输出中。如果我故意破坏绑定,我会得到一个绑定错误,但是使用上面的绑定,我不会得到任何错误,但它永远不会触发。

尝试放置
CreateCommand=new DelegateCommand(Create)
初始化组件()之前

创建命令后,尝试在构造函数中设置
DataContext=this
。@默认情况下,控件在
InitializeComponent()
方法中创建其绑定,此时CreateCommand未被分配。用户需要在
InitializeComponent()
之前移动分配,或者在分配命令后引发属性更改事件。
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");
        }
    }
}