2012-12-31 22 views
8

Użyto MVVM. Stworzyłem osobne menu "Ostatnie pliki", które pobierają elementy z wiązania. Wygląda na to, że:WPF: Dodaj polecenie wygenerowane automatycznie przez powiązanie elementów menu

enter image description here

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

Teraz chciałbym dodać polecenie, aby każdy z tych elementów generowanych automatycznie, co powinno uzyskać ścieżkę jako parametr polecenia i wykonać działania pliku importu przez kliknięcie .

Czy mógłbyś zasugerować, jak można to zrobić w sposób MVVM?

Odpowiedz

19

Znów znalazłem rozwiązanie samodzielnie. Próbowałem złożyć polecenie w niewłaściwy sposób, jak poniżej, i to nie działa:

  <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> 

Oto właściwe podejście. Nadal nie rozumiem, jak to działa, musisz nauczyć się WPF głęboko!

  <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: Ostateczna wersja

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 Światło Toolkit jest używany, RelayCommand idzie stamtąd:

 private ICommand _importRecentItemCommand; 

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

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

Ciesz

Powiązane problemy