Click here to Skip to main content
Click here to Skip to main content
Go to top

Basic MVVM Listbox Binding In WPF

, 11 Aug 2014
Rate this:
Please Sign up or sign in to vote.
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 do bind items from a directory to a listbox can use same methodoligy to bind any collection to the listbox. This is my first article so not sure how to do the formatting correctly. This same approach can be used for the combo box.

Using the code

This is a very basic overview of how to do binding to a list box, I have included the entire pattern i use to acheive my result.

// The ViewModelBase
public abstract class ViewModelBase : INotifyPropertyChanged
    {
        #region Property Changed Event Handler
        private void SetPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        public event PropertyChangedEventHandler PropertyChanged;
        #endregion Property Changed Event Handler
    }
// 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 = "File Name: {0}.".FormatString(this.fileName);
            return returnString;
        }
        #endregion String Override
    }
// 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
    }
// 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

First Draft 2014/08/12

License

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

Share

About the Author

Jdarmanovich
Software Developer
South Africa South Africa
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web01 | 2.8.140916.1 | Last Updated 12 Aug 2014
Article Copyright 2014 by Jdarmanovich
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid