WPF ListView

I have a Listview scripted as below.  It does pretty much all I need of it.  However when I save a new record I am unable to get it to display that change.  The data source is an ObserverableCollection and the new record is visible in the ObservableCollection just not on screen.

<ListBox x:Name="ProductListings" SelectedValue ="{Binding SelectedAction,Mode=TwoWay }" ItemsSource="{Binding ProductList,Mode=TwoWay}" DisplayMemberPath=" ProductName" HorizontalAlignment="Left" Height="134" Margin="10,36,0,0" VerticalAlignment="Top" Width="159"/>

Open in new window

LVL 1
AlyantoAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

apeterCommented:
If this is a property in your view  model , then raise propertychanged event by implementing "INotify....." interface.
0
Fernando SotoRetiredCommented:
The DisplayMemberPath you show is this, DisplayMemberPath=" ProductName", it seems you have an extra space at the beginning of the string, it should be, DisplayMemberPath="ProductName".
0
MikeTooleCommented:
For sure not the issue, but Mode=TwoWay just doesn't make sense for the ObservableCollection binding - first, it's the default for most properties; second, the source (VM property) will never be updated from the target (view property) anyway.
Can you post the code from your ViewModel that implements the collection?
0
Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

AlyantoAuthor Commented:
ViewModelBase
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Windows.Input;

namespace MarcoWPF.ViewModel
{
    public abstract class ViewModelBase : INotifyPropertyChanged, IDisposable, ICommand
    {
        protected ViewModelBase()
        {
        }

        #region INotifyPropertyChanged members
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChange(string PropertName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                var e = new PropertyChangedEventArgs(PropertName);
                handler(this, e);
            }
        }
        #endregion

        #region IDisposable Members
        public void Dispose()
        {
            this.Dispose();
        }
        protected virtual void OnDispose()
        {
        }
        #endregion

        #region ICommand Members
        public ICommand UpdateCommand
        {
            get;
            private set;
        }


        public bool CanExecute(object parameter)
        {
            throw new NotImplementedException();
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            throw new NotImplementedException();
        }
        #endregion

    }
}

Open in new window


MainWindowViewModel

      
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MarcoWPF.Model;
using System.Collections.ObjectModel;
using MarcoWPF.DataServices;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Input;
using MarcoWPF.Commands ;
using System.Windows;


namespace MarcoWPF.ViewModel 
{
    class MainWindowViewModel : ViewModelBase , ICommand
    {

        public MainWindowViewModel()
        {
            CommandNewRecord = new ProductNewRecord (this);
            CommandUpdateRecord = new ProductUpdateRecord (this);
            CommandSaveRecord = new ProductSaveRecord(this);
            productlist = MakeListOfProducts();
            Editable = true;
        }

        #region Interface Control
        private bool editable;
        public bool Editable
        {
            get { return editable; }
            private set { editable = value;
            OnPropertyChange("Editable");
            }
        }
        
        private bool savestate;
        public bool SaveState
        {
            get { return savestate; }
            private set{savestate = value;
            OnPropertyChange("SaveState");
            }
        }
        #endregion

        #region Button Behaviour
        public void NewRecord()
        {
            
           
            CurrentRecord = new Product() ;
 
            SaveState = true;
            
        }

        public void UpdateRecord()
        {
            
            try
            {
                if (EvaluateRecord(CurrentRecord))
                {
                    SaveState = true;
                    Editable = false;
                }
                else
                {
                    throw new Exception("The record to be saved has failed to so because it was incomplete");
                }
            }
            catch (Exception e)
            {
                System.Windows.MessageBox.Show(e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                SaveState = false;
                Editable = true;
            }
        }

        public void SaveRecord()
        {
            try
            {
                if (EvaluateRecord(CurrentRecord))
                {
                    try
                    {
                        DataTable ToSave = Product.ProductTableStructure;
                        DataRow RowSave = ToSave.NewRow();

                        RowSave["ProductCode"] = CurrentRecord.ProductCode;
                        RowSave["ProductName"] = CurrentRecord.ProductName;
                        RowSave["ProductType"] = CurrentRecord.ProductType;
                        RowSave["MinStkQty"] = CurrentRecord.MinStkQty;
                        RowSave["UOM"] = CurrentRecord.UOM ;
                        RowSave["Active"] = CurrentRecord.Active;
                        ToSave.Rows.Add(RowSave);

                        DataService.CRUD_DML_Proc(ToSave, "@Prod", "DMLProduct");

                        //Reset the product collection 
                        productlist = new ObservableCollection<Product>();

                        //The act of getting a count whilst the count of records is zero forces a data refresh.
                        //int i = ProductList.Count;
                        productlist = MakeListOfProducts();

                    }
                    catch (Exception dbe)
                    {
                        throw dbe;
                    }
                }
                else
                {
                    throw new Exception("The record to be saved has failed to so because it was incomplete");
                }
            }
            catch (Exception e)
            {
                System.Windows.MessageBox.Show(e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            { 
                SaveState = false; 
            }
            
        }

        private bool EvaluateRecord(Product currentRecord)
        {
            int CountFail = 0;

            if (string.IsNullOrWhiteSpace(CurrentRecord.ProductCode) || CurrentRecord.ProductCode == null)
            {
                CountFail += 1;
            }

            if (string.IsNullOrWhiteSpace(CurrentRecord.ProductName) || CurrentRecord.ProductName == null)
            {
                CountFail += 1;
            }

            if (string.IsNullOrWhiteSpace(CurrentRecord.UOM) || CurrentRecord.UOM == null )
            {
                CountFail += 1;
            }

            if ( CurrentRecord.ProductType == null )
            { 
                CountFail += 1; 
            }


            if (CountFail == 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public ICommand CommandNewRecord
        {
            get;
            set;
        }

        public ICommand CommandUpdateRecord
        {
            get;
            set;
        }

        public ICommand CommandSaveRecord
        {
            get;
            set;
        }

        #endregion 



        private Product currentrecord;
        public Product CurrentRecord
        {
            get
            {
                if (currentrecord == null)
                {
                    currentrecord = new Product();
                    
                }
                return currentrecord;
            }
            set { 
                currentrecord = value;
                SaveState = false; 
                if (currentrecord.ProductName  != null && currentrecord.ProductCode == null)
                {
                    currentrecord.ProductCode = currentrecord.ProductName.ToUpper().Replace(" ", "").Replace("A", "").Replace("E", "").Replace("E", "").Replace("I", "").Replace("O", "");             
                }
                OnPropertyChange("CurrentRecord"); 
            }           
        }

        private ProductType selectedproducttype;
        public ProductType SelectedProductType
        {
            get { return selectedproducttype; }
            set { selectedproducttype = value;
            if (selectedproducttype != null)
            {
                // CurrentRecord.ProductType = selectedproducttype.ProductsType;
                Product Prod = CurrentRecord;
                Prod.ProductType = selectedproducttype.ProductsType;
                CurrentRecord = Prod;
            }
            
            }
        }

        private UOM selecteduom;
        public UOM SelectedUOM
        {
            get { return selecteduom; }
            set { selecteduom = value;
            if (selecteduom != null)
            { 
                Product Prod = CurrentRecord;
                Prod.UOM = selecteduom.UOMs;
                CurrentRecord = Prod;
            }
            }
        }



        private Product selectedaction;
        public Product SelectedAction
        {
            get { return selectedaction; }
            set { selectedaction = value;
            CurrentRecord  = selectedaction;
            }
        }
        #region Product
        private ObservableCollection<Product> productlist;
        public ObservableCollection<Product> ProductList
        {
            get
            {
                return productlist;              
            }
            set
            {
                productlist = value;
                OnPropertyChange("ProductList");
            }
        }

     [b]   private ObservableCollection<Product> MakeListOfProducts()
        {
            ObservableCollection<Product> PList = new ObservableCollection<Product>();
            if (productlist == null || int.Parse(productlist.Count().ToString()) == 0)
            {
                PList = new ObservableCollection<Product>();
                List<SqlParameter> ParamList = new List<SqlParameter>();
                DataTable ProductTable = DataService.CRUD_DQL_Proc(ParamList, "ListProduct");

                foreach (DataRow row in ProductTable.Rows)
                {
                    PList.Add(new Product(row["ProductCode"].ToString(),
                        row["ProductName"].ToString(),
                        int.Parse(row["ProductType"].ToString()),
                        decimal.Parse(row["MinStkQty"].ToString()),
                        row["UOM"].ToString(),
                        bool.Parse(row["Active"].ToString()), getProductTypeName(int.Parse(row["ProductType"].ToString()))));
                }
            }

            return PList;
        }
[/b]
        #endregion
        
        #region ProductType

        private string getProductTypeName(Int32 productType)
        {
            IEnumerable<String> query = from val in ProductType
                                        where val.ProductsType == productType
                                        select val.ProductTypeName;

            string ret = query.First() ;
            return ret;
        
        }

        private ObservableCollection<ProductType> producttype;
        public ObservableCollection<ProductType> ProductType
        {
            get 
            {
                if (producttype == null)
                {
                    producttype = new ObservableCollection<ProductType>();
                    List<SqlParameter> ParamList = new List<SqlParameter>();
                    DataTable ProductTypeTable = DataService.CRUD_DQL_Proc(ParamList, "ListProductType");

                    foreach (DataRow row in ProductTypeTable.Rows)
                    {
                        Int32 x = Int32.Parse(row["ProductType"].ToString());
                        producttype.Add(new ProductType(Int32.Parse(row["ProductType"].ToString()),
                            row["ProductTypeName"].ToString()));
                    }

                } 
                return producttype ;
            }
        }
        #endregion

        #region UOM
        private ObservableCollection<UOM> uom;
        public ObservableCollection<UOM> UOMList
        {
            get
            {
                if (uom == null)
                {
                    uom = new ObservableCollection<UOM>();
                    List<SqlParameter> ParamList = new List<SqlParameter>();
                    DataTable UOMTable = DataService.CRUD_DQL_Proc(ParamList, "ListUOM");

                    foreach (DataRow row in UOMTable.Rows)
                    {
                        String sUOM = row["UOM"].ToString();
                        uom.Add(UOM.MakeUOM(row["UOM"].ToString()));
                    }
                }
                return uom;
            }
        }



        private UOM singleuom;
        public UOM SingleUOM
        {
            get
            {
                return singleuom;
            }
        }
        #endregion

              
        public bool CanExecute(object parameter)
        {
           
            throw new NotImplementedException();
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            throw new NotImplementedException();
        }

    }
}

Open in new window

0
AlyantoAuthor Commented:
Please note there are two encodings that look like [ b ] and [ /b ] these were an attempt to make bold the relevant code but have not rendered as expected.
0
MikeTooleCommented:
In SaveRecord() the product list is reset via ...

                        productlist = MakeListOfProducts();

However, this directly sets the private backing field for the list and therefore no call is made to OnPropertyChanged  to trigger WPF to requery the binding.
This change may fix your problem:

                        ProductList = MakeListOfProducts();


The ObservableCollection class allows automatic view of any additions/deletions in a collection, without the need to resend the whole collection to the using control. However, you're not using this support - whenever there is a change you're recreating the entire list, so you may as well use List<Product> as the collection type.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
AlyantoAuthor Commented:
Excellent spot Mike, thank you very much.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.