简体   繁体   English

WPF RelayCommand 在按钮单击时未触发

[英]WPF RelayCommand not firing on button click

I'm inexperienced with both WPF and MVVM so i'm most likeley missing something but when I click my button the command isn't firing.我对 WPF 和 MVVM 都没有经验,所以我很可能遗漏了一些东西,但是当我点击我的按钮时,命令没有触发。 I also have some menu controls on my page that i've setup the exact same way and when I click those, their commands work as expected.我的页面上还有一些菜单控件,我以完全相同的方式设置,当我单击它们时,它们的命令按预期工作。

I've tried attaching a click event handler to make sure the button is definitely being clicked which it is.我尝试附加一个单击事件处理程序以确保该按钮确实被单击了。 I've also tried attaching a different command that works on my menu control which didn't work on the button.我还尝试附加一个不同的命令,该命令适用于我的菜单控件,而该命令不适用于按钮。

<Button Grid.Row="1" Content="Add Note" 
                                        Command="{Binding InsertNoteCommand}"/>
public ICommand InsertNoteCommand { get; }

public MainViewModel()
{
    InsertNoteCommand = new RelayCommand(InsertNote);
}

private void InsertNote()
{
    Console.WriteLine("Note Inserted!");
}

I should also mention that i'm using MVVM Light我还应该提到我正在使用 MVVM Light

The debugging information is very useful to know but in the end I solved the problem by pointing the binding to the data context.调试信息非常有用,但最后我通过将绑定指向数据上下文来解决问题。

<Button x:Name="AddNewNoteBtn" Grid.Row="1" Content="Add Note" 
                                        Command="{Binding Path=DataContext.InsertNoteCommand,  ElementName=_window}"/>

If anybody has comments on how I can improve this I would really appreciate it.如果有人对我如何改进这一点有意见,我将不胜感激。 Thanks!谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM