Click here to Skip to main content
15,891,951 members
Articles / Programming Languages / C#
Tip/Trick

Basic MVVM Listbox Binding in WPF

Rate me:
Please Sign up or sign in to vote.
4.24/5 (7 votes)
11 Aug 2014CPOL 63K   9   2
Basic MVVM pattern for binding items to a listbox in WPF

Introduction

Basic MVVM pattern for binding items to a listbox in WPF, this pattern can also be used for Winforms just how you set the control will be done in code behind.

Background

This example shows how to bind items from a directory to a listbox. You can use the same methodology to bind any collection to the listbox. This is my first tip, so I am not sure how to do the formatting correctly. This same approach can be used for the combobox.

Using the Code

This is a very basic overview of how to do binding to a listbox. I have included the entire pattern I use to achieve my result.

C#
// The ViewModelBase
public abstract class ViewModelBase : INotifyPropertyChanged
    {
        #region Property Changed Event Handler
        public void SetPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        public event PropertyChangedEventHandler PropertyChanged;
        #endregion Property Changed Event Handler
    }
C#
// Basic Model

public class FileObject : ViewModelBase
    {
        #region Properties
        #region Location
        private string location = string.Empty;
        public string Location
        {
            get { return location; }
            set
            {
                if (value != this.location)
                    location = value;
                this.SetPropertyChanged("Location");
            }
        }
        #endregion Location

        #region FileName
        private string fileName = string.Empty;
        public string FileName
        {
            get { return fileName; }
            set
            {
                if (value != this.fileName)
                    fileName = value;
                this.SetPropertyChanged("FileName");
            }
        }
        #endregion FileName
        #endregion Properties

        #region String Override
        public override string ToString()
        {
            //.FormatString(this string myString) is an extension.
            string returnString = string.Empty;
            if (this.fileName != string.Empty)
                returnString = String.Format("File Name: {0}.",this.fileName);
            return returnString;
        }
        #endregion String Override
    }
C#
// View Model

public class ViewModel : ViewModelBase
    {
        #region Constructor
        public ViewModel()
        {
            setFiles();
        }
        #endregion Constructor

        #region Properties
        #region SelectedFileObject
        private FileObject selectedFileObjects;
        public FileObject SelectedFileObject
        {
            get { return selectedFileObjects; }
            set
            {
                if (value != this.selectedFileObjects)
                    selectedFileObjects = value;
                this.SetPropertyChanged("SelectedFileObject");
            }
        }
        #endregion SelectedFileObject

        #region FileObjectCollection
        private ObservableCollection<FileObject> fileObjectCollection;
        public ObservableCollection<FileObject> FileObjectCollection
        {
            get { return fileObjectCollection; }
            set
            {
                if (value != this.fileObjectCollection)
                    fileObjectCollection = value;
                this.SetPropertyChanged("FileObjectCollection");
            }
        }
        #endregion FileObjectCollection

        #region Path
        //Use Your own path
        private string path = @"C:\Users\pcName\Downloads\Gifs";
        public string Path
        {
            get { return path; }
            set
            {
                if (value != this.path)
                    path = value;
                this.SetPropertyChanged("Path");
            }
        }
        #endregion Path
        #endregion Properties

        #region Mehods
        #region void setFiles()
        private void setFiles()
        {
            if (this.path != string.Empty)
            {
                DirectoryInfo dInfo = new DirectoryInfo(this.path);
                //use any extension you want.
                FileInfo[] fInfo = dInfo.GetFiles("*.gif");
                fInfo.Cast<FileInfo>().ToList().ForEach(setFileObjectCollection());
            }
        }
        #endregion void setFiles()

        #region Action<FileInfo> setFileObjectCollection()
        private Action<FileInfo> setFileObjectCollection()
        {
            this.fileObjectCollection = new ObservableCollection<FileObject>();
            return f => this.fileObjectCollection.Add(new FileObject 
			{ FileName = f.Name, Location = f.DirectoryName });
        }
        #endregion Action<FileInfo> setFileObjectCollection()
        #endregion Mehods
    }
C#
// View

<Window 
    x:Class="GifViewer.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="GifViewer" Height="350" Width="525">
    <Window.DataContext>
        <local:ViewModel/>
    </Window.DataContext>
    <Grid>
        <ListBox ItemsSource="{Binding FileObjectCollection}" 
		SelectedItem="{Binding SelectedFileObject}"/>
    </Grid>
</Window>

History

  • 2014/08/12: First draft

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
South Africa South Africa
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionIt does not work at all Pin
Member 113031399-Jul-15 20:39
Member 113031399-Jul-15 20:39 
Bug"this.SetPropertyChanged("FileName")" cannot be used due to protection Pin
CoderMan127-May-15 5:26
CoderMan127-May-15 5:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.