【问题标题】:WPF - clicking on a button inside an user control doesn't call the command, and neither does clicking on the control itselfWPF - 单击用户控件内的按钮不会调用命令,单击控件本身也不会
【发布时间】:2016-02-16 22:36:28
【问题描述】:

我在将任何命令绑定到我的用户控件时遇到了严重问题。一切都可以编译,但永远不会调用该命令。我尝试了两种方法 - 首先,我尝试将命令绑定到我的控件内的按钮,当我无法执行此操作时,我尝试将命令绑定到控件本身的 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>

现在,视图的 xaml 文件的简化(不包括不相关的属性)数据模板部分(如果重要,它具有数据上下文),我在其中使用此控件:

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

为了完整起见,我将包含来自视图模型的命令。

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,它只是从两个函数创建一个命令(并且可以在其他任何地方使用)。

你能告诉我为什么单击按钮没有任何反应以及如何解决它吗?

【问题讨论】:

    标签: wpf mvvm user-controls command


    【解决方案1】:

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

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

    其中 local:AddImage 是将 DataContext 设置为视图模型的视图的名称..

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多