WPF 按钮命令未触发,我错过了什么? [英] WPF Button Command not firing, what am I missing?

查看:32
本文介绍了WPF 按钮命令未触发,我错过了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发这个帖子感觉很糟糕,因为我看到了大量类似的帖子,但在浏览完所有帖子后,我仍然无法完全诊断出我的问题.我拥有的是一个 WPF 应用程序,它使用 MVVM 模式设计并使用 RelayCommand() 实现命令.

I feel bad posting this because I see a ton of similar posts, but after going through them all I can't quite diagnose my issue still. What I have is a WPF app designed with the MVVM pattern and using a RelayCommand() implementation for commands.

在我的用户控件的 XAML 中,我在这里设置了数据上下文:

In my user control's XAML I set the data context here :

<UserControl.DataContext>
    <viewModel:SidePanelViewModel />
</UserControl.DataContext>

然后在 XAML 中我有这个片段,我在其中分配了一个按钮的命令

Then further down in the XAML I have this snippet where I assign a button's command

<TextBlock FontWeight="Bold" Margin="0,0,0,10">Service List</TextBlock>
<ListBox MaxHeight="100"
        ItemsSource="{Binding ServiceList}"
        SelectedItem="{Binding ServiceToRemove}">
</ListBox>
<Button HorizontalAlignment="Left" Width="60" Margin="0,10"
        Command="{Binding RemoveServiceCommand}">Remove</Button>

我将按钮绑定到我在 SidePanelViewModel 中定义的命令 RemoveApplicationCommand :

I am binding the button to the Command RemoveApplicationCommand which I define in the SidePanelViewModel here :

public ICommand RemoveServiceCommand
{
    get { return new RelayCommand(RemoveService, CanRemoveService); }
}

private void RemoveService()
{
    ServerList.Remove(ServiceToRemove);
}

private bool CanRemoveService()
{
    return true;
}

问题

如果我调试,RemoveServiceCommand 的 getter 会在按钮启动时到达,但是当我点击按钮时代码没有到达它.我之前有一个非常相似的实现(或者我认为),所以这真的让我感到困惑.如何让命令在点击时触发?

If I debug, the getter for RemoveServiceCommand will be reached when the button starts up, but when I click the button the code doesn't reach it. I had a very similar implementation (or so I think) working before, so this is really puzzling me. How can I get the command to fire on click?

推荐答案

原来调试器一直在检查 RemoveService,但我没有在那里放置断点.我的 RemoveService 实现中有一个错误的名称 ServerList.Remove() 应该是 ServiceList.Remove().我假设调试器会在 RemoveServiceCommand 属性的 getter 中遇到一个断点,但事实证明,当您单击按钮时它并没有遇到该断点.

Turns out the debugger was going over RemoveService the entire time but I had not put a breakpoint there. I had a wrong name in my RemoveService implementation ServerList.Remove() should have been ServiceList.Remove(). I assumed the debugger would hit a breakpoint in the RemoveServiceCommand property's getter but it turns out it doesn't hit that when you click the button.

这篇关于WPF 按钮命令未触发,我错过了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆