RelayCommand 未在 MenuItem 单击 WPF MVVM 上触发
我的 WPF 表单上有一个运行导入例程的菜单项,我已将命令属性绑定到视图模型中的 ICommand 属性,但由于某种原因该方法不会触发。
这是 xaml:
<Menu Height="21"
Margin="0,-2,0,0"
VerticalAlignment="Top"
Grid.ColumnSpan="2">
<MenuItem Header="File" Command="{Binding ImportFileCommand}">Import</MenuItem>
</Menu>
这是在我的视图模型中:
private ICommand importfilecommand;
public ICommand ImportFileCommand
{
get
{
if (this.importfilecommand == null)
{
this.importfilecommand = new RelayCommand(parm => ImportFile());
}
return this.importfilecommand;
}
}
private void ImportFile()
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Tab Files (*.tab)|*.tab*";
if (dialog.ShowDialog() == true)
{
// MessageBox.Show(dialog.FileName);
}
}
这是我用于表单上所有按钮的模式,但菜单项不起作用。我是否遗漏了什么或者菜单项必须以不同的方式完成?
谢谢。
I have a menu item on my WPF form that runs an import routine, I have bound the command property to a ICommand property in my view model but for some reason the method won't fire.
This is the xaml:
<Menu Height="21"
Margin="0,-2,0,0"
VerticalAlignment="Top"
Grid.ColumnSpan="2">
<MenuItem Header="File" Command="{Binding ImportFileCommand}">Import</MenuItem>
</Menu>
And this is in my view model:
private ICommand importfilecommand;
public ICommand ImportFileCommand
{
get
{
if (this.importfilecommand == null)
{
this.importfilecommand = new RelayCommand(parm => ImportFile());
}
return this.importfilecommand;
}
}
private void ImportFile()
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Tab Files (*.tab)|*.tab*";
if (dialog.ShowDialog() == true)
{
// MessageBox.Show(dialog.FileName);
}
}
This is the pattern that I have used for all my buttons on the form but the menu item just won't work. Am I missing something or do menu items have to be done differently?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将 XAML 更改为
在您的示例中,MenuItem 元素的“Import”内容隐式创建父 File MenuItem 的子 MenuItem。该子 MenuItem 没有定义 Command 属性,因此无法执行。显然,父菜单项上定义的命令的可执行性被子菜单扩展功能覆盖。
Change your XAML to
In your example, the "Import" content of the MenuItem element implicitly creates a child MenuItem of the parent File MenuItem. This child MenuItem has no Command property defined and so is unable to be executed. Apparently the executability of the Command defined on the parent MenuItem is overridden by the sub-menu expansion functionality.