Solved

WPF ListView

Posted on 2014-10-06
7
177 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 62

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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 

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
 

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
 

Author Closing Comment

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

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
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 demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

746 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now