2017-05-06 2 views
2

Je voudrais demander comment remplir la liste en utilisant le modèle MVVM Je suis débutant dans le modèle mvvm, j'apprends plus de choses à faire que de lire. Je l'ai fait avant d'utiliser wpf mais j'utilise le code derrière.Populate Listview en utilisant mvvm

J'utilise Mvvm Light. Ce que je veux parcourir l'emplacement du dossier, puis remplir le listview avec les fichiers à l'intérieur

Jusqu'à présent, je l'ai déjà un dossier Parcourir

j'ai ce code

public class OpenFileDialogVM : ViewModelBase 
    { 
     public static RelayCommand OpenCommand { get; set; } 
     private string _selectedPath; 
     public string SelectedPath 
     { 
      get { return _selectedPath; } 
      set 
      { 
       _selectedPath = value; 
       RaisePropertyChanged("SelectedPath"); 
      } 
     } 

     private string _defaultPath; 

     public OpenFileDialogVM() 
     { 
      RegisterCommands(); 
     } 

     public OpenFileDialogVM(string defaultPath) 
     { 
      _defaultPath = defaultPath; 
      RegisterCommands(); 
     } 

     private void RegisterCommands() 
     { 
      OpenCommand = new RelayCommand(ExecuteOpenFileDialog); 
     } 

     private void ExecuteOpenFileDialog() 
     { 
      var dialog = new FolderBrowserDialog(); 
      dialog.ShowDialog(); 

      SelectedPath = dialog.SelectedPath; 
     } 
    } 

et j'ai ce code pour le contrôle utilisateur

<UserControl x:Class="MvvmLight1.FolderDialog" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:vm="clr-namespace:MvvmLight1" 
      xmlns:local="clr-namespace:MvvmLight1" 
      mc:Ignorable="d" d:DesignWidth="300" Height="186.916" > 
    <Grid> 
     <Grid.RowDefinitions> 
      <RowDefinition Height="90*"/> 
      <RowDefinition Height="97*"/> 
     </Grid.RowDefinitions> 
     <Grid> 
      <TextBox Text="{Binding SelectedPath}" /> 
     </Grid> 
     <Grid Grid.Row="1" > 
      <Button Command="vm:OpenFileDialogVM.OpenCommand" >Browse</Button> 
     </Grid> 

    </Grid> 
</UserControl> 

jusqu'à présent, la navigation fonctionne. Ma question est comment puis-je appeler ce code. après la sélection du dossier afin que je puisse remplir ma listview?

private void Call(string selectedpath) 
     { 
      try 
      { 
       var allFiles = Directory.GetFiles(selectedpath, "*", SearchOption.AllDirectories); 

       foreach (var item in allFiles) 
       { 
        System.Console.WriteLine(item); 
        //code for populating listview 
       } 
      } 
      catch (System.Exception ex) 
      { 
       System.Console.WriteLine(ex.StackTrace); 
       throw ex; 
      } 
     } 

Merci pour le temps.

+0

Note: ajouter une référence pour System.Windows.Forms –

+0

Oui. pouvez-vous m'aider ou me donner un extrait de code comment appeler le code en utilisant MVVM? Après avoir sélectionné un dossier Merci – classname13

+0

Reproduire dans mon IDE maintenant. Pour référence future, voir [MCVE] (https://stackoverflow.com/help/mcve) sur la façon d'écrire une question (c'est un très bon travail cependant). –

Répondre

1
  • Make Files une collection publique observable. Élevé l'événement PropertyChanged.
  • Définissez le datacontext de la fenêtre sur votre viewmodel. Lier à la propriété viewmodel dans xaml.

CS

using System; 
    using System.ComponentModel; 
    using System.IO; 
    using System.Windows; 
    using System.Windows.Input; 
    using System.Collections.ObjectModel; 

    namespace StackOverflow_PopulateListView 
    { 
     /// <summary> 
     /// Interaction logic for MainWindow.xaml 
     /// </summary> 
     public partial class MainWindow : Window 
     { 
      public MainWindow() 
      { 
       InitializeComponent(); 
       DataContext = new OpenFileDialogVM(); 
      } 
     } 

     public class OpenFileDialogVM : ViewModelBase 
     { 
      public static RelayCommand OpenCommand { get; set; } 
      private string _selectedPath = "Enter a Path"; 
      public string SelectedPath 
      { 
       get { return _selectedPath; } 
       set 
       { 
        _selectedPath = value; 
        OnPropertyChanged("SelectedPath"); 
       } 
      } 

      private ObservableCollection<string> _files = new ObservableCollection<string>() { "Tits", "balls", "ass", "tits" }; 
      public ObservableCollection<string> Files 
      { 
       get { return _files; } 
       set 
       { 
        _files = value; 
        OnPropertyChanged("Files"); 
       } 
      } 

      private ICommand _selectFileCommand; 
      public ICommand SelectFileCommand 
      { 
       get 
       { 
        return _selectFileCommand ?? (_selectFileCommand = new RelayCommand(() => Call(SelectedPath))); 
       } 
       protected set 
       { 
        _selectFileCommand = value; 
       } 
      } 

      public void Call(string selectedpath) 
      { 
       try 
       { 
        Files = new ObservableCollection<string>(Directory.GetFiles(selectedpath, "*", SearchOption.AllDirectories)); 
       } 
       catch (Exception ex) 
       { 
        Console.WriteLine(ex.StackTrace); 
        throw ex; 
       } 
      } 
     } 

     public class RelayCommand : ICommand 
     { 
      public Action Act { get; set; } 

      /// <summary> Occurs when the target of the Command should reevaluate whether or not the Command can be executed. </summary> 
      public event EventHandler CanExecuteChanged; 

      public RelayCommand(Action act) 
      { 
       Act = act; 
      } 

      /// <summary> Returns a bool indicating if the Command can be exectued with the given parameter </summary> 
      public bool CanExecute(object obj) 
      { 
       return true; 
      } 

      /// <summary> Send a ICommand.CanExecuteChanged </summary> 
      public void ChangeCanExecute() 
      { 
       object sender = this; 
       EventArgs eventArgs = null; 
       CanExecuteChanged(sender, eventArgs); 
      } 

      /// <summary> Invokes the execute Action </summary> 
      public void Execute(object obj) 
      { 
       Act(); 
      } 
     } 

     /// <summary> 
     /// Extremely generic ViewModelBase; for copy-pasting into almost any MVVM project 
     /// </summary> 
     public class ViewModelBase : INotifyPropertyChanged 
     { 
      public event PropertyChangedEventHandler PropertyChanged; 

      /// <summary> 
      /// Fires PropertyChangedEventHandler, for bindables 
      /// </summary> 
      protected virtual void OnPropertyChanged(string name) 
      { 
       PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); 
      } 

     } 
    } 

XAML

<Window x:Class="StackOverflow_PopulateListView.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:local="clr-namespace:StackOverflow_PopulateListView" 
    mc:Ignorable="d" 
    Title="MainWindow" Height="350" Width="525" 
    > 
    <Grid> 
     <Grid.RowDefinitions> 
      <RowDefinition Height="8*"/> 
      <RowDefinition Height="1*"/> 
      <RowDefinition Height="1*"/> 
     </Grid.RowDefinitions> 

     <ListView ItemsSource="{Binding Files}" Grid.Row="0"> 
      <ListView.ItemTemplate> 
       <DataTemplate> 
        <TextBlock Text="{Binding}"/> 
       </DataTemplate> 
      </ListView.ItemTemplate> 
     </ListView> 

     <TextBox Grid.Row="1" 
        Text="{Binding SelectedPath}" 
       /> 

     <Button Grid.Row="2" 
        Content="Call" 
        Command="{Binding SelectFileCommand}" 
       /> 

    </Grid> 
</Window> 
+0

Je viens de résumer le problème à "databind la liste xaml à une propriété de fichiers dans le viewmodel". Cela inclut tout ce dont vous avez besoin pour compiler seul. Bonne chance! –

+0

Merci qui a fonctionné. Et maintenant j'ai seulement besoin de chercher ce que sont ces codes et quand je vais les utiliser. Merci beaucoup – classname13

1

Votre modèle de vue devrait avoir un ObservableCollection des noms de fichiers

public ObservableCollection<string> FileNames { get; } 
    = new ObservableCollection<string>(); 

qui est renseigné lorsqu'un répertoire est sélectionné:

var files = Directory.EnumerateFiles(selectedpath, "*", SearchOption.AllDirectories); 

FileNames.Clear(); 

foreach (var file in files) 
{ 
    FileNames.Add(file); 
} 

alors vous lier la propriété ItemsSource d'un ListBox à cette collection :

<ListBox ItemsSource="{Binding FileNames}"/> 
+0

avec ce code. quand et comment vais-je appeler ce code en utilisant mvvm pattern? Merci beaucoup – classname13

+0

"quand un répertoire est sélectionné", c'est-à-dire quand la propriété SelectedPath change. – Clemens