2012-12-31 7 views
8

MVVM viene utilizzato. Ho creato il menu separato 'File recenti' che ottiene i suoi articoli dal binding. Sembra che:WPF: aggiunge un comando a generato automaticamente da voci di menu vincolanti

enter image description here

 <MenuItem Header="_Recent files" ItemsSource="{Binding RecentFiles, Converter={StaticResource RecentFilesToListOfStringsConverter}, Mode=OneWay}" > 
     </MenuItem> 

Ora, vorrei aggiungere Comando a ciascuno dei tali elementi generati automaticamente, che dovrebbe ottenere il percorso come parametro di comando ed eseguire l'azione file di importazione con un clic .

Potrebbe per favore suggerire come può essere fatto in modo MVVM?

risposta

19

Ancora, ho trovato la soluzione da solo. Ho cercato di mettere il comando in modo sbagliato come qui di seguito, e non funziona:

  <MenuItem Header="_Recent files" ItemsSource="{Binding RecentFiles, Converter={StaticResource RecentFilesToListOfStringsConverter}, Mode=OneWay}" > 
      <MenuItem.ItemContainerStyle> 
       <Style TargetType="{x:Type MenuItem}"> 
        <Setter Property="Command" Value="{Binding ImportRecentItemCommand}" /> 
       </Style> 
      </MenuItem.ItemContainerStyle> 
     </MenuItem> 

Ecco l'approccio giusto. Ancora non capisco come funziona, devi imparare profondamente WPF!

  <MenuItem Header="_Recent files" ItemsSource="{Binding RecentFiles, Converter={StaticResource RecentFilesToListOfStringsConverter}, Mode=OneWay}" > 
      <MenuItem.ItemContainerStyle> 
       <Style TargetType="{x:Type MenuItem}"> 
        <Setter Property="Command" Value="{Binding DataContext.ImportRecentItemCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type MenuItem}, AncestorLevel=1}}" /> 
       </Style> 
      </MenuItem.ItemContainerStyle> 
     </MenuItem> 

EDIT: La versione finale

XAML:

  <MenuItem Header="_Recent files" ItemsSource="{Binding RecentFiles, Converter={StaticResource RecentFilesToListOfStringsConverter}, Mode=OneWay}" > 
      <MenuItem.ItemContainerStyle> 
       <Style TargetType="{x:Type MenuItem}"> 
        <Setter Property="Command" Value="{Binding DataContext.ImportRecentItemCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type MenuItem}, AncestorLevel=1}}" /> 
        <Setter Property="CommandParameter" Value="{Binding}" /> 
       </Style> 
      </MenuItem.ItemContainerStyle> 
     </MenuItem> 

ViewModel: MVVM Luce Toolkit viene utilizzato, RelayCommand va da lì:

 private ICommand _importRecentItemCommand; 

     public ICommand ImportRecentItemCommand 
     { 
      get { return _importRecentItemCommand ?? (_importRecentItemCommand = new RelayCommand<object>(ImportRecentItemCommandExecuted)); } 
     } 

     private void ImportRecentItemCommandExecuted(object parameter) 
     { 
      MessageBox.Show(parameter.ToString()); 
     } 

Godetevi