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

时间:2015-11-15 21:05:59

标签: wpf mvvm user-controls command

我遇到了将任何命令绑定到用户控件的严重问题。一切都在编译,但命令永远不会被调用。我尝试了两种方法 - 首先,我尝试将命令绑定到控件内的按钮,当我无法执行此操作时,我尝试将命令绑定到控件本身的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”,而Hash是另一个依赖属性):

<Button Command="{Binding ElementName=Control, Path=CloseCommand}" CommandParameter="{Binding ElementName=Control, Path=Hash}">
                <TextBlock Text="X"/></Button>

现在,一个简化的(不包含的无关属性)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);}
}

RelayCommand类来自MicroMVVM,它只是从两个函数创建一个命令(并在其他地方工作)。

你能告诉我为什么点击按钮什么都不做以及如何修复它?

1 个答案:

答案 0 :(得分:0)

似乎即使我浪费了几个小时,我也很快问这个问题。在发布之后几分钟,我意识到我在ItemTemplate中的绑定是错误的。 问题是我使用了ElementName而不是RelativeSource:

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

where local:AddImage是将DataContext设置为viewmodel的视图的名称..

相关问题