?
Solved

WPF ListView

Posted on 2014-10-06
7
Medium Priority
?
187 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Tutorials alone can't teach real engineering

So we built better training tools.

-Hands-on Labs
-Instructor Mentoring
-Scenario-Based Tests
-Dedicated Cloud Servers

All at your fingertips. What are you waiting for?

 
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 2000 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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…
Suggested Courses

752 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