2011-06-23 42 views
0

我需要幫助來弄清爲什麼我的命令在菜單項上不起作用。我一直在使用Google的解決方案,而且在這裏也找不到。但可能是因爲我的知識(初學者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> 

下面是視圖模型的代碼。

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值爲空。這是如果我使用按鈕,而不是。

編輯: 額外信息:我使用MVVMLight的RelayCommand。

回答

1

可能發生的情況是,當您選擇菜單項時,TextBox仍然有焦點。默認情況下,當控件失去焦點時WPF中的綁定更新(以便更新不會持續發生,就像PropertyChange是更新類型時那樣)。當您使用該按鈕時,TextBox失去焦點,因爲按鈕得到它。

您可以通過在窗口上添加另一個控件(任何類型)並在選擇菜單項之前單擊它來測試此項。

如果解決了這個問題,那麼最簡單的解決方法是將綁定更新類型更改爲PropertyChange(這可以在設計器的綁定選項區域中完成)。

+0

它很棒!我感到很傻。無論如何,我正在做一個記事本,你覺得每次改變文本框的時候打電話給propertychange是個好主意嗎? 謝謝! –

+0

@Shulhi:我看不出任何真正的缺點。只要你的屬性是一個簡單的'string'屬性,除了將值存儲在內存中之外什麼都不做,那麼你就不必擔心它。 –

+0

再次感謝。最後一個問題,如果我使用剪切/複製/粘貼等內置命令,它可以很好地工作。但是像Close這樣的內置命令是禁用的,儘管我已經將IsEnabled設置爲true。我可以使用自定義命令,但如果可以的話,我想使用內置的命令。 –