我需要帮助来弄清楚为什么我的命令在菜单项上不起作用。我一直在谷歌上搜索解决方案,在这里也发现了一些。但可能因为我的知识(初学者WPF),我仍然无法解决它。任何帮助表示赞赏!
它适用于按钮,但不适用于菜单项。
XAML:
<Window x:Class="WPFBeginner.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="349" Width="259">
<Grid>
<Grid.RowDefinitions />
<Grid.ColumnDefinitions />
<Menu Height="22" HorizontalAlignment="Left" Name="menu1" VerticalAlignment="Top" Width="237" Margin="0,1,0,0">
<MenuItem Header="_File" >
<MenuItem Header="Save As" Command="{Binding SaveCommand}"/>
<Separator />
<MenuItem Command="Close" />
</MenuItem>
<MenuItem Header="_Edit">
<MenuItem Command="Undo" />
<Separator />
<MenuItem Command="Cut" />
<MenuItem Command="Copy" />
<MenuItem Command="Paste" />
<Separator />
<MenuItem Command="SelectAll" />
</MenuItem>
</Menu>
<TextBox Height="217" HorizontalAlignment="Left" Margin="0,21,0,0" Name="txtBox1" VerticalAlignment="Top" Width="238"
Text="{Binding Note.Data}" />
<!--button works fine-->
<Button Content="Save" Height="23" HorizontalAlignment="Left" Margin="12,244,0,0" Name="button1" VerticalAlignment="Top" Width="75"
Command="{Binding SaveCommand}"/>
</Grid>
</Window>
这是 ViewModel 的代码。
class NoteViewModel : INotifyPropertyChanged
{
public ICommand SaveCommand { get; set; }
public NoteViewModel()
{
SaveCommand = new RelayCommand(Save);
Note = new NoteModel();
}
private NoteModel note;
public NoteModel Note
{
get { return note; }
set
{
if (note != value)
{
note = value;
RaisedPropertyChanged("Note");
}
}
}
private void Save()
{
SaveFileDialog file = new SaveFileDialog();
if ((bool)file.ShowDialog())
{
File.WriteAllText(file.FileName, Note.Data, Encoding.UTF8);
}
}
#region ...INPC
public event PropertyChangedEventHandler PropertyChanged;
private void RaisedPropertyChanged(string p)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(p));
}
#endregion
}
我调试了一下,结果发现命令(SaveCommand
--> Save()
)被执行了,但是值为Note.Data
null。如果我改用按钮,那就是这样。
编辑:额外信息:我使用来自 MVVMLight 的 RelayCommand。