Friday, June 21, 2013

ListBox Data template in WPF MVVM sample



This post talks about using Data Template in WPF – MVVM. As an example I am using ListBox control. The items will be added to listbox based on data template bindings. As basic configuration create a WPF proect. Add View Models folder. I have added another project in the same solution – BusinessLayer. This actually returns list of Tasks that need to be displayed in ListBox. The final solution structure is as follows –
 

Business Layer has a class Task and TaskManager. The TaskManager class is used to create a list of Tasks which will be displayed in ListBox. The Task.cs is as follows –
public class Task
    {
        public string Name { get; set; }
 
        public string Description { get; set; } 

        public int Priority { get; set; }
    }
The TaskManager.cs contains the method to get the list of tasks. As it is very simple; I am skipping it. As part of this sample I have created a ViewModelBase class which contains the implementation of INotifyPropertyChanged  and my specific view model inherits from this base class. The code of my view model class is as follows -  
public class ViewModelBase : INotifyPropertyChanged
    {
       #region INotifyPropertyChanged implementation
        public event PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion
    }
My view model will contain following code –
public class MainWindowsViewModel : ViewModelBase
    {       
        #region Class variables
        private IList<Task> _tasks = null;
        #endregion
 
        #region Initialize view model
        public MainWindowsViewModel()
        {
            //get the list of tasks and assign to list view
            Tasks = TaskManager.GetTasks();
        }            
        #endregion        
 
        #region Properties
      //This property used to bind to List
        public IList<Task> Tasks
        {
            get
            {
                return _tasks;
            }
            set
            {
                _tasks = value;
                NotifyPropertyChanged("Tasks");
            }
        }
        #endregion
    }
Bind the view model to XAML from code behind file. Now we will declare the DataTemplate in XAML file.
<Window.Resources>       
        <DataTemplate x:Key="MyTasks">
            <Border Name="border" BorderBrush="Aqua" BorderThickness="1"
          Padding="5" Margin="5">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition />
                        <ColumnDefinition />
                    </Grid.ColumnDefinitions>
                    <TextBlock Grid.Row="0" Grid.Column="0" Text="Task Name:"/>
                    <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Path=Name}" />
                    <TextBlock Grid.Row="1" Grid.Column="0" Text="Description:"/>
                    <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Path=Description}"/>
                    <TextBlock Grid.Row="2" Grid.Column="0" Text="Priority:"/>
                    <TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding Path=Priority}"/>
                </Grid>
            </Border>
         </DataTemplate>
    </Window.Resources>   

    <StackPanel>
        <TextBlock FontSize="20" Text="My Task List:"/>       
        <ListBox Width="400" Margin="10"
             ItemsSource="{Binding Tasks}"
                 ItemTemplate="{StaticResource MyTasks }"/>

    </StackPanel>
The output is as shown below –
 

This is how you can use MVVM with Data Template using List Box.
Hope it helps.
Cheers…

Happy Templating!!!

No comments:

Post a Comment