locked
How to update observatble collection at runtime using wpf mvvm RRS feed

  • Question

  • mainwindow.xaml:
    <Window x:Class="sample.MainPage"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainPage" Height="485" Width="525">
        <Grid Margin="0,0,0,20">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="auto"/>
            </Grid.RowDefinitions>
            <ListView Name="UserGrid" Grid.Row="1" Margin="4,178,12,13"  ItemsSource="{Binding UserList}"  >
                <ListView.View>
                    <GridView x:Name="grdTest">
                        <GridViewColumn Header="UserId" DisplayMemberBinding="{Binding UserId}"  Width="50"/>
                        <GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}"  Width="80" />
                        <GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}" Width="100" />
                        <GridViewColumn Header="City" DisplayMemberBinding="{Binding City}" Width="80" />
                        <GridViewColumn Header="State" DisplayMemberBinding="{Binding State}" Width="80" />
                        <GridViewColumn Header="Country" DisplayMemberBinding="{Binding Country}" Width="100" />
                    </GridView>
                </ListView.View>
            </ListView>
            <TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,7,0,0" Name="txtUserId" VerticalAlignment="Top" Width="178" Text="{Binding ElementName=UserGrid,Path=SelectedItem.UserId}" />
            <TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,35,0,0" Name="txtFirstName" VerticalAlignment="Top" Width="178" Text="{Binding ElementName=UserGrid,Path=SelectedItem.FirstName}" />
            <TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,62,0,0" Name="txtLastName" VerticalAlignment="Top" Width="178" Text="{Binding ElementName=UserGrid,Path=SelectedItem.LastName}" />
            <Label Content="UserId" Grid.Row="1" HorizontalAlignment="Left" Margin="12,12,0,274" Name="label1" />
            <Label Content="Last Name" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,60,0,0" Name="label2" VerticalAlignment="Top" />
            <Label Content="First Name" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,35,0,0" Name="label3" VerticalAlignment="Top" />
            <Button Content="Update" Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="310,40,0,0" Name="btnUpdate" 
                    VerticalAlignment="Top" Width="141"
                    Command="{Binding Path=ButtonCommand}"  />
            <TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,143,0,0" x:Name="txtCity" VerticalAlignment="Top" Width="178" Text="{Binding SelectedItem.City, ElementName=UserGrid}" />
            <Label Content="Country" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,141,0,0" x:Name="label2_Copy" VerticalAlignment="Top" />
            <TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,88,0,0" x:Name="txtCountry" VerticalAlignment="Top" Width="178" Text="{Binding SelectedItem.Country, ElementName=UserGrid}" />
            <Label Content="City" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,86,0,0" x:Name="label2_Copy1" VerticalAlignment="Top" />
            <TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,115,0,0" x:Name="txtSTate" VerticalAlignment="Top" Width="178" Text="{Binding SelectedItem.State, ElementName=UserGrid}" />
            <Label Content="State" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,113,0,0" x:Name="label2_Copy2" VerticalAlignment="Top" />
        </Grid>
    </Window>
    ViewModel.cs:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Collections.ObjectModel;
    using WpfApplication3.Commands;
    using System.Windows.Input;
    using System.Windows;
    namespace sample
    {
        public class ViewModel:Helper
        {
            private ObservableCollection<Helper> userlist;
            public ViewModel()
            {
                userlist = new ObservableCollection<Helper>
                {
                    new Helper{UserId=1,FirstName="Manju",LastName="Nath",City="Guntakal",State="Andhra Pradesh",Country="India"},
                    new Helper{UserId=2,FirstName="Dare",LastName="Viswas",City="Chennai",State="Tamil Nadu",Country="India"},
                    new Helper{UserId=3,FirstName="Alphonsa",LastName="KD",City="Kottayam",State="Kerala",Country="India"},
                    new Helper{UserId=4,FirstName="Sarath",LastName="Kumar",City="Noida",State="New Delhi",Country="India"},
                    new Helper{UserId=5,FirstName="AB",LastName="De Villers",City="Munda",State="Cape Town",Country="South Africa"},
                    new Helper{UserId=6,FirstName="Kevin",LastName="Pieterson",City="Miami",State="The Oval",Country="England"}
                };
             
            }
            public ObservableCollection<Helper> UserList
            {
                get { return userlist; }
                set { 
                    userlist = value;
                    OnPropertyChanged("UserList");
                }
            }
            private DelegateCommand _ButtonCommand;
            public ICommand ButtonCommand
            {
                get
                {
                    if (_ButtonCommand != null)
                    {
                        _ButtonCommand = new DelegateCommand(new Action(SignInExecuted));
                    }
                    return _ButtonCommand;
                }
            }
            public void SignInExecuted()
            {
                MessageBox.Show("Data Updated Successfully");
            }
        }
    }
    Model:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ComponentModel;
    namespace sample
    {
         public class Model:INotifyPropertyChanged
         {
             public event PropertyChangedEventHandler PropertyChanged;
             public void OnPropertyChanged(string propertyName)
             {
                 if (PropertyChanged != null)
                 {
                     PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                 }
             }
         }
    }
    Helper.cs:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    namespace sample
    {
        public class Helper:Model
        {
            private int userId=0;
            private string firstName=string.Empty;
            private string lastName=string.Empty;
            private string city=string.Empty;
            private string state=string.Empty;
            private string country=string.Empty;
            public int UserId
            {
                get
                {
                    return userId;
                }
                set
                {
                    userId = value;
                    OnPropertyChanged("UserId");
                }
            }
            public string FirstName
            {
                get
                {
                    return firstName;
                }
                set
                {
                    firstName = value;
                    OnPropertyChanged("FirstName");
                }
            }
            public string LastName
            {
                get
                {
                    return lastName;
                }
                set
                {
                    lastName = value;
                    OnPropertyChanged("LastName");
                }
            }
            public string City
            {
                get
                {
                    return city;
                }
                set
                {
                    city = value;
                    OnPropertyChanged("City");
                }
            }
            public string State
            {
                get
                {
                    return state;
                }
                set
                {
                    state = value;
                    OnPropertyChanged("State");
                }
            }
            public string Country
            {
                get
                {
                    return country;
                }
                set
                {
                    country = value;
                    OnPropertyChanged("Country");
                }
            }                          
        }
    }

    Hi,

         I want to implement add and delete operations for my application.on adding the data to employee table at runtime,how to update the observable collection in view model,how to achieve that.how to perform delete operation by clicking the selected item in datagrid.please help me,above i have pasted my coding.Thanks in advance.

    Regards,

    Chaya Manjunath.


    Chaya Manjunath

    Monday, April 23, 2012 5:18 AM

Answers

  • Hi Chaya,

    Please see the code snippet below for ur query.

    XAML:
    
    <Window x:Class="SandBox.Window57"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:SandBox"
        Title="Window57" Height="600" Width="300">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="*"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"></ColumnDefinition>
                <ColumnDefinition Width="*"></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <Label x:Name="lblFirstName" Content="First Name" Grid.Row="0" Grid.Column="0"></Label>
            <TextBox x:Name="txtFirstName" Grid.Row="0" Grid.Column="1" Width="150" Margin = "5" HorizontalAlignment="Left" Text="{Binding Path = Employee.FirstName, UpdateSourceTrigger = PropertyChanged}" ></TextBox>
            <Label x:Name="lblMiddleName" Content="Middle Name" Grid.Row="1" Grid.Column="0"></Label>
            <TextBox x:Name="txtMiddleName" Grid.Row="1" Grid.Column="1" Width="150" Margin = "5" HorizontalAlignment="Left" Text="{Binding Path = Employee.MiddleName}"></TextBox>
            <Label x:Name="lblLastName" Content="Last Name" Grid.Row="2" Grid.Column="0"></Label>
            <TextBox x:Name="txtLastName" Grid.Row="2" Grid.Column="1" Width="150" Margin = "5" HorizontalAlignment="Left" Text="{Binding Path = Employee.LastName}"></TextBox>
            <Button x:Name="btnAdd" Grid.Row="3" Grid.Column="1" Content="Add" Width="150" Margin = "5" HorizontalAlignment="Left" Command="{Binding Path = AddCommand}" CommandParameter="{Binding Path = Employee}"></Button>
            <!--<CheckBox x:Name="chkAdd" Grid.Row="3" Grid.Column="1" Content="Add" Width="150" Margin = "5" HorizontalAlignment="Left" Command="{Binding Path = AddCommand}" CommandParameter="{Binding Path = Employee}"></CheckBox>-->
            <ListView x:Name="lvEmployees" Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="2" ItemsSource="{Binding Path = EmployeeList}"
                      local:SelectionBehavior.SelectionChanged="{Binding DisplayCommand}">
                <ListView.View>
                    <GridView x:Name="gvEmployees">
                        <GridViewColumn x:Name="gvcFirstName" Header="First Name" DisplayMemberBinding="{Binding Path = FirstName,  Mode = OneTime}"></GridViewColumn>
                        <GridViewColumn x:Name="gvcMiddleName" Header="Middle Name" DisplayMemberBinding="{Binding Path = MiddleName,  Mode = OneTime}"></GridViewColumn>
                        <GridViewColumn x:Name="gvcLastName" Header="Last Name" DisplayMemberBinding="{Binding Path = LastName,  Mode = OneTime}"></GridViewColumn>
                    </GridView>
                </ListView.View>
            </ListView>
            <Label x:Name="lblDisplayFirstName" Content="First Name" Grid.Row="5" Grid.Column="0"></Label>
            <TextBox x:Name="lblDisplayFirstNameValue" IsReadOnly="True" Width="150" Margin = "5" HorizontalAlignment="Left" Text="{Binding Path = DisplayEmployee.FirstName}" Grid.Row="5" Grid.Column="1"></TextBox>
            <Label x:Name="lblDisplayMiddleName" Content="Middle Name" Grid.Row="6" Grid.Column="0"></Label>
            <TextBox x:Name="lblDisplayMiddleNameValue" IsReadOnly="True" Width="150" Margin = "5" HorizontalAlignment="Left" Text="{Binding Path = DisplayEmployee.MiddleName}" Grid.Row="6" Grid.Column="1"></TextBox>
            <Label x:Name="lblDisplayLastName" Content="Last Name" Grid.Row="7" Grid.Column="0"></Label>
            <TextBox x:Name="lblDisplayLastNameValue" IsReadOnly="True" Width="150" Margin = "5" HorizontalAlignment="Left" Text="{Binding Path = DisplayEmployee.LastName}" Grid.Row="7" Grid.Column="1"></TextBox>
        </Grid>
    </Window>
    
    
    CodeBehind:
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Shapes;
    using System.ComponentModel;
    using System.Collections.ObjectModel;
    using NUnit.Framework;
    using System.Windows.Controls.Primitives;
    
    namespace SandBox
    {
        /// <summary>
        /// Interaction logic for Window57.xaml
        /// </summary>
        public partial class Window57 : Window
        {
            public Window57ViewModel ViewModel { get; set; }
    
            public Window57()
            {
    
                InitializeComponent();
                ViewModel = new Window57ViewModel();
                this.DataContext = ViewModel;
            }
        }
    
        public class Window57ViewModel : INotifyPropertyChanged
        {
            #region Member Variables
            private EmployeeClass m_Employee;
    
            private EmployeeClass m_DisplayEmployee;
    
            private ICommand m_AddCommand;
    
            private ICommand m_DisplayCommand;
            #endregion
    
            #region Properties
    
            public EmployeeClass Employee
            {
                get
                {
                    return m_Employee;
                }
                set
                {
                    m_Employee = value;
                    OnPropertyChanged("Employee");
                }
            }
    
            public ObservableCollection<EmployeeClass> EmployeeList { get; set; }
    
            public EmployeeClass DisplayEmployee
            {
                get
                {
                    return m_DisplayEmployee;
                }
                set
                {
                    m_DisplayEmployee = value;
                    OnPropertyChanged("DisplayEmployee");
                }
            }
    
            public ICommand AddCommand
            {
                get
                {
                    if (m_AddCommand == null)
                        m_AddCommand = new AddEmployee(EmployeeList);
                    return m_AddCommand;
                }
                set
                {
                    m_AddCommand = value;
                }
            }
    
            public ICommand DisplayCommand
            {
                get
                {
                    if (m_DisplayCommand == null)
                        m_DisplayCommand = new DisplayEmployeeClass(this);
                    return m_DisplayCommand;
                }
                set
                {
                    m_DisplayCommand = value;
                }
            }
    
            #endregion
    
            #region Constructors
    
            public Window57ViewModel()
            {
                Employee = new EmployeeClass();
                EmployeeList = new ObservableCollection<EmployeeClass>();
                DisplayEmployee = new EmployeeClass();
            }
    
            #endregion
    
            #region INotifyPropertyChanged Members
    
            public event PropertyChangedEventHandler PropertyChanged;
    
            #endregion
    
            protected virtual void OnPropertyChanged(string propertyName)
            {
                if (this.PropertyChanged != null)
                    this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    
        public class AddEmployee : ICommand
        {
            #region Properties
            public ObservableCollection<EmployeeClass> EmployeeList { get; set; }
            #endregion
    
            #region Constructors
            public AddEmployee(ObservableCollection<EmployeeClass> m_EmployeeList)
            {
                EmployeeList = m_EmployeeList;
            }
            #endregion
    
            #region ICommand Members
    
            public bool CanExecute(object parameter)
            {
                if (parameter != null)
                {
                    EmployeeClass emp = new EmployeeClass();
                    emp.FirstName = ((EmployeeClass)parameter).FirstName;
                    emp.MiddleName = ((EmployeeClass)parameter).MiddleName;
                    emp.LastName = ((EmployeeClass)parameter).LastName;
                    return emp.FirstName.Length > 3;
                }
                return true;
            }
    
            event EventHandler ICommand.CanExecuteChanged
            {
                add { CommandManager.RequerySuggested += value; }
                remove { CommandManager.RequerySuggested -= value; }
            }
    
            public void Execute(object parameter)
            {
                EmployeeClass emp = new EmployeeClass();
                emp.FirstName = ((EmployeeClass)parameter).FirstName;
                emp.MiddleName = ((EmployeeClass)parameter).MiddleName;
                emp.LastName = ((EmployeeClass)parameter).LastName;
    
                if (string.IsNullOrEmpty(emp.FirstName) && string.IsNullOrEmpty(emp.MiddleName) && string.IsNullOrEmpty(emp.LastName))
                {
                    IDialogService dialog = new DialogService();
                    dialog.ShowMessageBox("Invalid Values.....", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
    
                EmployeeList.Add(emp);
            }
    
            #endregion
        }
    
        public class DisplayEmployeeClass : ICommand
        {
            #region Properties
            public Window57ViewModel ViewModel { get; set; }
            #endregion
    
            #region Constructors
            public DisplayEmployeeClass(Window57ViewModel m_ViewModel)
            {
                ViewModel = m_ViewModel;
            }
            #endregion
    
            #region ICommand Members
    
            public bool CanExecute(object parameter)
            {
                return true;
            }
    
            public event EventHandler CanExecuteChanged;
    
            public void Execute(object parameter)
            {
                ViewModel.DisplayEmployee = ((EmployeeClass)parameter);
            }
    
            #endregion
        }
    
        public class EmployeeClass
        {
            #region Properties
    
            public string FirstName { get; set; }
    
            public string MiddleName { get; set; }
    
            public string LastName { get; set; }
    
            #endregion
    
            #region Constructors
    
            public EmployeeClass()
            {
                FirstName = MiddleName = LastName = string.Empty;
            }
    
            #endregion
        }
    
        public interface IDialogService
        {
            MessageBoxResult ShowMessageBox(
                string messageBoxText,
                string caption,
                MessageBoxButton button,
                MessageBoxImage icon);
        }
    
        public class DialogService : IDialogService
        {
            public MessageBoxResult ShowMessageBox(
                string messageBoxText,
                string caption,
                MessageBoxButton button,
                MessageBoxImage icon)
            {
                return MessageBox.Show(messageBoxText, caption, button, icon);
            }
        }
    
        [TestFixture]
        public class Window57_Test
        {
            Window57ViewModel ViewModel = null;
    
            [SetUp]
            public void Setup()
            {
                ViewModel = new Window57ViewModel();
            }
    
            [Test]
            public void TestWindow57()
            {
                if (ViewModel.AddCommand.CanExecute(null))
                {
                    EmployeeClass employee = new EmployeeClass();
                    employee.FirstName = "Parth";
                    employee.LastName = "Shah";
                    ViewModel.AddCommand.Execute(employee);
                    Assert.Contains(employee, ViewModel.EmployeeList);
                }
                else
                {
                    Assert.Fail();
                }
            }
    
            [TearDown]
            public void TearDown()
            {
                ViewModel = null;
            }
        }
    
        public class SelectionBehavior
        {
            public static DependencyProperty SelectionChangedProperty = DependencyProperty.RegisterAttached("SelectionChanged", typeof(ICommand), typeof(SelectionBehavior), new UIPropertyMetadata(SelectionBehavior.SelectedItemChanged));
    
            public static void SetSelectionChanged(DependencyObject target, ICommand value)
            {
                target.SetValue(SelectionBehavior.SelectionChangedProperty, value);
            }
    
            static void SelectedItemChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
            {
                Selector element = target as Selector;
                if (element == null)
                    throw new InvalidOperationException("This behavior can be attached to Selector item only.");
                if ((e.NewValue != null) && (e.OldValue == null))
                {
                    element.SelectionChanged += SelectionChanged;
                }
                else if ((e.NewValue == null) && (e.OldValue != null))
                {
                    element.SelectionChanged -= SelectionChanged;
                }
            }
    
            static void SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
            {
                UIElement element = (UIElement)sender;
                ICommand command = (ICommand)element.GetValue(SelectionBehavior.SelectionChangedProperty);
                command.Execute(((Selector)sender).SelectedItem);
            }
        }
    }
    

    In the code snippet above by clicking the add button, Employee object is added to the observablecollection in ViewModel. Same methodology can be applied for delete operation as well.

    Hope it helps!

    Please mark it as an answer if it resolves ur query.

    Regards,

    Parth Shah


    Regards, Parth Shah

    • Proposed as answer by parth.shah Monday, April 23, 2012 6:18 AM
    • Marked as answer by Annabella Luo Friday, May 4, 2012 9:01 AM
    Monday, April 23, 2012 6:17 AM

All replies

  • Hi Chaya,

    Please see the code snippet below for ur query.

    XAML:
    
    <Window x:Class="SandBox.Window57"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:SandBox"
        Title="Window57" Height="600" Width="300">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="*"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"></ColumnDefinition>
                <ColumnDefinition Width="*"></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <Label x:Name="lblFirstName" Content="First Name" Grid.Row="0" Grid.Column="0"></Label>
            <TextBox x:Name="txtFirstName" Grid.Row="0" Grid.Column="1" Width="150" Margin = "5" HorizontalAlignment="Left" Text="{Binding Path = Employee.FirstName, UpdateSourceTrigger = PropertyChanged}" ></TextBox>
            <Label x:Name="lblMiddleName" Content="Middle Name" Grid.Row="1" Grid.Column="0"></Label>
            <TextBox x:Name="txtMiddleName" Grid.Row="1" Grid.Column="1" Width="150" Margin = "5" HorizontalAlignment="Left" Text="{Binding Path = Employee.MiddleName}"></TextBox>
            <Label x:Name="lblLastName" Content="Last Name" Grid.Row="2" Grid.Column="0"></Label>
            <TextBox x:Name="txtLastName" Grid.Row="2" Grid.Column="1" Width="150" Margin = "5" HorizontalAlignment="Left" Text="{Binding Path = Employee.LastName}"></TextBox>
            <Button x:Name="btnAdd" Grid.Row="3" Grid.Column="1" Content="Add" Width="150" Margin = "5" HorizontalAlignment="Left" Command="{Binding Path = AddCommand}" CommandParameter="{Binding Path = Employee}"></Button>
            <!--<CheckBox x:Name="chkAdd" Grid.Row="3" Grid.Column="1" Content="Add" Width="150" Margin = "5" HorizontalAlignment="Left" Command="{Binding Path = AddCommand}" CommandParameter="{Binding Path = Employee}"></CheckBox>-->
            <ListView x:Name="lvEmployees" Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="2" ItemsSource="{Binding Path = EmployeeList}"
                      local:SelectionBehavior.SelectionChanged="{Binding DisplayCommand}">
                <ListView.View>
                    <GridView x:Name="gvEmployees">
                        <GridViewColumn x:Name="gvcFirstName" Header="First Name" DisplayMemberBinding="{Binding Path = FirstName,  Mode = OneTime}"></GridViewColumn>
                        <GridViewColumn x:Name="gvcMiddleName" Header="Middle Name" DisplayMemberBinding="{Binding Path = MiddleName,  Mode = OneTime}"></GridViewColumn>
                        <GridViewColumn x:Name="gvcLastName" Header="Last Name" DisplayMemberBinding="{Binding Path = LastName,  Mode = OneTime}"></GridViewColumn>
                    </GridView>
                </ListView.View>
            </ListView>
            <Label x:Name="lblDisplayFirstName" Content="First Name" Grid.Row="5" Grid.Column="0"></Label>
            <TextBox x:Name="lblDisplayFirstNameValue" IsReadOnly="True" Width="150" Margin = "5" HorizontalAlignment="Left" Text="{Binding Path = DisplayEmployee.FirstName}" Grid.Row="5" Grid.Column="1"></TextBox>
            <Label x:Name="lblDisplayMiddleName" Content="Middle Name" Grid.Row="6" Grid.Column="0"></Label>
            <TextBox x:Name="lblDisplayMiddleNameValue" IsReadOnly="True" Width="150" Margin = "5" HorizontalAlignment="Left" Text="{Binding Path = DisplayEmployee.MiddleName}" Grid.Row="6" Grid.Column="1"></TextBox>
            <Label x:Name="lblDisplayLastName" Content="Last Name" Grid.Row="7" Grid.Column="0"></Label>
            <TextBox x:Name="lblDisplayLastNameValue" IsReadOnly="True" Width="150" Margin = "5" HorizontalAlignment="Left" Text="{Binding Path = DisplayEmployee.LastName}" Grid.Row="7" Grid.Column="1"></TextBox>
        </Grid>
    </Window>
    
    
    CodeBehind:
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Shapes;
    using System.ComponentModel;
    using System.Collections.ObjectModel;
    using NUnit.Framework;
    using System.Windows.Controls.Primitives;
    
    namespace SandBox
    {
        /// <summary>
        /// Interaction logic for Window57.xaml
        /// </summary>
        public partial class Window57 : Window
        {
            public Window57ViewModel ViewModel { get; set; }
    
            public Window57()
            {
    
                InitializeComponent();
                ViewModel = new Window57ViewModel();
                this.DataContext = ViewModel;
            }
        }
    
        public class Window57ViewModel : INotifyPropertyChanged
        {
            #region Member Variables
            private EmployeeClass m_Employee;
    
            private EmployeeClass m_DisplayEmployee;
    
            private ICommand m_AddCommand;
    
            private ICommand m_DisplayCommand;
            #endregion
    
            #region Properties
    
            public EmployeeClass Employee
            {
                get
                {
                    return m_Employee;
                }
                set
                {
                    m_Employee = value;
                    OnPropertyChanged("Employee");
                }
            }
    
            public ObservableCollection<EmployeeClass> EmployeeList { get; set; }
    
            public EmployeeClass DisplayEmployee
            {
                get
                {
                    return m_DisplayEmployee;
                }
                set
                {
                    m_DisplayEmployee = value;
                    OnPropertyChanged("DisplayEmployee");
                }
            }
    
            public ICommand AddCommand
            {
                get
                {
                    if (m_AddCommand == null)
                        m_AddCommand = new AddEmployee(EmployeeList);
                    return m_AddCommand;
                }
                set
                {
                    m_AddCommand = value;
                }
            }
    
            public ICommand DisplayCommand
            {
                get
                {
                    if (m_DisplayCommand == null)
                        m_DisplayCommand = new DisplayEmployeeClass(this);
                    return m_DisplayCommand;
                }
                set
                {
                    m_DisplayCommand = value;
                }
            }
    
            #endregion
    
            #region Constructors
    
            public Window57ViewModel()
            {
                Employee = new EmployeeClass();
                EmployeeList = new ObservableCollection<EmployeeClass>();
                DisplayEmployee = new EmployeeClass();
            }
    
            #endregion
    
            #region INotifyPropertyChanged Members
    
            public event PropertyChangedEventHandler PropertyChanged;
    
            #endregion
    
            protected virtual void OnPropertyChanged(string propertyName)
            {
                if (this.PropertyChanged != null)
                    this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    
        public class AddEmployee : ICommand
        {
            #region Properties
            public ObservableCollection<EmployeeClass> EmployeeList { get; set; }
            #endregion
    
            #region Constructors
            public AddEmployee(ObservableCollection<EmployeeClass> m_EmployeeList)
            {
                EmployeeList = m_EmployeeList;
            }
            #endregion
    
            #region ICommand Members
    
            public bool CanExecute(object parameter)
            {
                if (parameter != null)
                {
                    EmployeeClass emp = new EmployeeClass();
                    emp.FirstName = ((EmployeeClass)parameter).FirstName;
                    emp.MiddleName = ((EmployeeClass)parameter).MiddleName;
                    emp.LastName = ((EmployeeClass)parameter).LastName;
                    return emp.FirstName.Length > 3;
                }
                return true;
            }
    
            event EventHandler ICommand.CanExecuteChanged
            {
                add { CommandManager.RequerySuggested += value; }
                remove { CommandManager.RequerySuggested -= value; }
            }
    
            public void Execute(object parameter)
            {
                EmployeeClass emp = new EmployeeClass();
                emp.FirstName = ((EmployeeClass)parameter).FirstName;
                emp.MiddleName = ((EmployeeClass)parameter).MiddleName;
                emp.LastName = ((EmployeeClass)parameter).LastName;
    
                if (string.IsNullOrEmpty(emp.FirstName) && string.IsNullOrEmpty(emp.MiddleName) && string.IsNullOrEmpty(emp.LastName))
                {
                    IDialogService dialog = new DialogService();
                    dialog.ShowMessageBox("Invalid Values.....", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
    
                EmployeeList.Add(emp);
            }
    
            #endregion
        }
    
        public class DisplayEmployeeClass : ICommand
        {
            #region Properties
            public Window57ViewModel ViewModel { get; set; }
            #endregion
    
            #region Constructors
            public DisplayEmployeeClass(Window57ViewModel m_ViewModel)
            {
                ViewModel = m_ViewModel;
            }
            #endregion
    
            #region ICommand Members
    
            public bool CanExecute(object parameter)
            {
                return true;
            }
    
            public event EventHandler CanExecuteChanged;
    
            public void Execute(object parameter)
            {
                ViewModel.DisplayEmployee = ((EmployeeClass)parameter);
            }
    
            #endregion
        }
    
        public class EmployeeClass
        {
            #region Properties
    
            public string FirstName { get; set; }
    
            public string MiddleName { get; set; }
    
            public string LastName { get; set; }
    
            #endregion
    
            #region Constructors
    
            public EmployeeClass()
            {
                FirstName = MiddleName = LastName = string.Empty;
            }
    
            #endregion
        }
    
        public interface IDialogService
        {
            MessageBoxResult ShowMessageBox(
                string messageBoxText,
                string caption,
                MessageBoxButton button,
                MessageBoxImage icon);
        }
    
        public class DialogService : IDialogService
        {
            public MessageBoxResult ShowMessageBox(
                string messageBoxText,
                string caption,
                MessageBoxButton button,
                MessageBoxImage icon)
            {
                return MessageBox.Show(messageBoxText, caption, button, icon);
            }
        }
    
        [TestFixture]
        public class Window57_Test
        {
            Window57ViewModel ViewModel = null;
    
            [SetUp]
            public void Setup()
            {
                ViewModel = new Window57ViewModel();
            }
    
            [Test]
            public void TestWindow57()
            {
                if (ViewModel.AddCommand.CanExecute(null))
                {
                    EmployeeClass employee = new EmployeeClass();
                    employee.FirstName = "Parth";
                    employee.LastName = "Shah";
                    ViewModel.AddCommand.Execute(employee);
                    Assert.Contains(employee, ViewModel.EmployeeList);
                }
                else
                {
                    Assert.Fail();
                }
            }
    
            [TearDown]
            public void TearDown()
            {
                ViewModel = null;
            }
        }
    
        public class SelectionBehavior
        {
            public static DependencyProperty SelectionChangedProperty = DependencyProperty.RegisterAttached("SelectionChanged", typeof(ICommand), typeof(SelectionBehavior), new UIPropertyMetadata(SelectionBehavior.SelectedItemChanged));
    
            public static void SetSelectionChanged(DependencyObject target, ICommand value)
            {
                target.SetValue(SelectionBehavior.SelectionChangedProperty, value);
            }
    
            static void SelectedItemChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
            {
                Selector element = target as Selector;
                if (element == null)
                    throw new InvalidOperationException("This behavior can be attached to Selector item only.");
                if ((e.NewValue != null) && (e.OldValue == null))
                {
                    element.SelectionChanged += SelectionChanged;
                }
                else if ((e.NewValue == null) && (e.OldValue != null))
                {
                    element.SelectionChanged -= SelectionChanged;
                }
            }
    
            static void SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
            {
                UIElement element = (UIElement)sender;
                ICommand command = (ICommand)element.GetValue(SelectionBehavior.SelectionChangedProperty);
                command.Execute(((Selector)sender).SelectedItem);
            }
        }
    }
    

    In the code snippet above by clicking the add button, Employee object is added to the observablecollection in ViewModel. Same methodology can be applied for delete operation as well.

    Hope it helps!

    Please mark it as an answer if it resolves ur query.

    Regards,

    Parth Shah


    Regards, Parth Shah

    • Proposed as answer by parth.shah Monday, April 23, 2012 6:18 AM
    • Marked as answer by Annabella Luo Friday, May 4, 2012 9:01 AM
    Monday, April 23, 2012 6:17 AM
  • Hi Chaya,

    Any updates over this?

    If ur query is resolved please close the post and mark it as an answer.

    Regards,

    Parth Shah


    Regards, Parth Shah

    Tuesday, April 24, 2012 4:50 AM
  • Hi,

         It is very difficult to understand.can you please provide some simple for this application.i need add and delete operations to perform in my application.if possible please do the operations with my application.Thanks in advance.

    Regards,

    Chaya Manjunath


    Chaya Manjunath

    Tuesday, April 24, 2012 5:04 AM
  • Hi Chaya,

    this way u can achieve in a simpler manner

    public void AddUser(Helper user)
    {
    var tempUsers=  usrList.ToList();
    tempUsers.Add(user);
    usrList=null;
    usrList=tempUsers.ToObseravaleCollection<Helper>()
                
    }

    for this you need to write a global function of ToObservableCollection

    Check this



    By Sanz. -- If you find this post helpful then please "Vote as Helpful" and "Mark As Answer".

    Tuesday, April 24, 2012 5:16 AM
  • Hi Chaya,

    ObservableCollection<T> implements INotifyCollectionChanged which informs a registered event handler about changes in the collection (add,remove,sort of items). However the DataGrid must know if a property of one of your business-objects has changed to update the value in the grid. For this, INotifyPropertyChanged is needed.
    ObservableCollection<T> implements also INotifyCollectionChanged. However this can only be used to be informed if a property of the collection has been changed. There is no mechanism that let the collection detect if your business object has been changed.

    And the solution parth give to you is about add data into ObservableCollection manually.

    So I'm marking that as Answer, if you have any concerns or new findings; please feel free to let me know.
    Best regards.


    Annabella Luo[MSFT]
    MSDN Community Support | Feedback to us


    Friday, May 4, 2012 9:03 AM