Solved

WPF ListView

Posted on 2014-10-06
7
180 Views
Last Modified: 2014-10-11
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

0
Comment
Question by:Alyanto
7 Comments
 
LVL 25

Expert Comment

by:apeter
ID: 40365968
If this is a property in your view  model , then raise propertychanged event by implementing "INotify....." interface.
0
 
LVL 63

Expert Comment

by:Fernando Soto
ID: 40366017
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
 
LVL 27

Expert Comment

by:MikeToole
ID: 40366700
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
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
LVL 1

Author Comment

by:Alyanto
ID: 40369763
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
 
LVL 1

Author Comment

by:Alyanto
ID: 40369769
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
 
LVL 27

Accepted Solution

by:
MikeToole earned 500 total points
ID: 40371286
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
 
LVL 1

Author Closing Comment

by:Alyanto
ID: 40374698
Excellent spot Mike, thank you very much.
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

803 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question