WPF-单击用户控件内的按钮不会';不要调用命令,也不要单击控件本身

WPF-单击用户控件内的按钮不会';不要调用命令,也不要单击控件本身,wpf,mvvm,user-controls,command,Wpf,Mvvm,User Controls,Command,我在将任何命令绑定到用户控件时遇到了严重问题。一切都可以编译,但从未调用该命令。我尝试了两种方法-首先,我尝试将命令绑定到控件内的按钮,当我无法执行时,我尝试将命令绑定到控件本身的inputcommand,以查看它是否可以工作。没有。控件本身在ItemsControl中,以防出现问题。 这是我所做工作的简化版本。在控件的xaml.cs文件中: public static readonly DependencyProperty CloseCommandProperty = Dependen

我在将任何命令绑定到用户控件时遇到了严重问题。一切都可以编译,但从未调用该命令。我尝试了两种方法-首先,我尝试将命令绑定到控件内的按钮,当我无法执行时,我尝试将命令绑定到控件本身的inputcommand,以查看它是否可以工作。没有。控件本身在ItemsControl中,以防出现问题。 这是我所做工作的简化版本。在控件的xaml.cs文件中:

    public static readonly DependencyProperty CloseCommandProperty = DependencyProperty.Register(
      "CloseCommand",
      typeof(ICommand),
      typeof(Thumbnail),
      new UIPropertyMetadata(null)
    );

    public ICommand CloseCommand
    {
        get { return (ICommand)GetValue(CloseCommandProperty); }
        set { SetValue(CloseCommandProperty, value); }
    }
在UserControl的xaml文件中,出现问题的按钮(UserControl具有Name=“Control”,哈希是另一个依赖项属性):


现在,一个简化的(不包括无关属性)datatemplate是视图的xaml文件的一部分(如果有必要的话,它有一个datacontext),在这里我使用这个控件:

<ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <local:Thumbnail Hash="{Binding Hash}"
                                         CloseCommand="{Binding ElementName=Control, Path=DataContext.RemoveImageCommand}"/>
                        </DataTemplate>
        </ItemsControl.ItemTemplate>

为了完整起见,我将包含viewmodel中的命令

private bool CanRemoveImageCommandExecute(string hash)
{
    return true;
}
private void RemoveImageCommandExecute(string hash)
{
    MessageBox.Show("ABC","ABC");
}
public ICommand RemoveImageCommand
{
    get { return new RelayCommand<string>(RemoveImageCommandExecute, CanRemoveImageCommandExecute);}
}
private bool CanRemoveImageCommandExecute(字符串哈希)
{
返回true;
}
私有void RemoveImageCommandExecute(字符串哈希)
{
MessageBox.Show(“ABC”、“ABC”);
}
公共ICommand RemoveImageCommand
{
获取{返回新的RelayCommand(RemoveImageCommandExecute,CanRemoveImageCommandExecute);}
}
RelayCommand类来自MicroMVVM,它只是从两个函数创建一个命令(在其他任何地方都可以使用)


你能告诉我为什么点击按钮没有任何作用以及如何修复它吗?

看起来,尽管我在这上面浪费了几个小时,但我还是太快了,没有问这个问题。发布几分钟后,我意识到我在ItemTemplate中的绑定是错误的。 问题是我使用了ElementName而不是RelativeSource:

CloseCommand="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=local:AddImage} 
其中local:AddImage是将DataContext设置为viewmodel的视图的名称

CloseCommand="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=local:AddImage}