Listbox is not Populating using binding

2019-07-17 09:05发布

问题:

I am trying to convert my existing program in c# wpf, using mvvm pattern.

The first part is select the Folder location of the files to be process and populate the listbox

I found an example here using Mvvm Light: WPF OpenFileDialog with the MVVM pattern?

the example in the link above is selecting a Folder.

this is the structure of my project

this is the code of my FileListView.xaml

<UserControl x:Class="MvvmLight1.Views.FilesListView"
             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:local="clr-namespace:MvvmLight1.Views"
             mc:Ignorable="d" 
             d:DesignHeight="300" Width="730.029">

    <Grid>
        <ListBox ItemsSource="{Binding FileNames}" Margin="5,5,5,5"/>

    </Grid>
</UserControl>

this is my list which reside in ViewModel\OpenFileDialogVM.cs

public System.Collections.ObjectModel.ObservableCollection<string> FileNames { get; }
    = new System.Collections.ObjectModel.ObservableCollection<string>();

this is my code for populating the list. but it doesn't work

var files = System.IO.Directory.EnumerateFiles(SelectedPath, "*", System.IO.SearchOption.AllDirectories);

            FileNames.Clear();

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

What is wrong with my code above?


Code Update:

On my folder structure I have ViewModel Folder and inside it I have OpenFileDialogVm.css

but why is it that the IDE only recognize the ViewModelLocator.

I even Build the project.

I even set the DataContext in the CodeBehind of FileListView user control but still it doesn't populate the listbox

public partial class FilesListView : UserControl
    {
        public FilesListView()
        {
            DataContext = new OpenFileDialogVM();
            InitializeComponent();

        }
    }

回答1:

Add it to your UserControl:

<UserControl
.....
xmlns:viemodels="clr-namespace:MvvmLight1.ViewModels"
/>
    <UserControl.DataContext>
        <viemodels:OpenFileDialogVM/>
    </UserControl.DataContext>
....
</UserControl>