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

标签 wpf mvvm user-controls command

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

现在, View 的 xaml 文件的简化(不包括不相关的属性)数据模板部分(如果重要,它具有数据上下文),我在其中使用此控件:
<ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <local:Thumbnail Hash="{Binding Hash}"
                                         CloseCommand="{Binding ElementName=Control, Path=DataContext.RemoveImageCommand}"/>
                        </DataTemplate>
        </ItemsControl.ItemTemplate>

为了完整起见,我将包含来自 View 模型的命令。
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,它只是从两个函数创建一个命令(并且在其他任何地方都可以使用)。

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

最佳答案

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

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

其中 local:AddImage 是将 DataContext 设置为 viewmodel 的 View 的名称。

关于WPF - 单击用户控件内的按钮不会调用命令,单击控件本身也不会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33725055/

相关文章:

c# - 将 List<Model> 转换为 ObservableCollection<ViewModel>

c# - 我的数据绑定(bind)怎么会写出 Length 属性?

c# - WPF 数据绑定(bind) - "Custom Type Descriptor"示例

c# - 使用模型类的特定字段填充 DataGrid

wpf - 如何动态地将 ViewModel 连接到其适当的 View?

.net - 使用 ElementHost 在 Winform 应用程序中托管 WPF UserControl 有什么缺点吗?

c# - WPF 依赖属性 ObservableCollection 显示多个值

c# - Windows开发如何快速学习Autofac?

c# - 如何将 GET 函数传递到 View/ViewModel?如何将数据绑定(bind)到 View (仅使用 C# 代码)?

c# - WPF 用户控件的加载事件多次触发