Load collection view using button binding

Kran2022 406 Reputation points
2023-01-16T10:09:29.97+00:00

Hello All: Morning

By loading collectionview as View binded to the datagird works using below code works but i would like to load the datagrid view by button click, so i added a button binding but the datagrid view is empty from button click:

How can i load the collection view using button click binding? thanks for your help.

Then added button in the UI to click on the button to read the pricing file and display it in the datagrid but nothing displayed in the datagrid view:

Button to click to read the pricing file but te datagrid view is empty:

Button click:

  <Button x:Name="breadxml"  HorizontalAlignment="Center" Margin="62,10" Width="76"   Command="{Binding Command}" CommandParameter="ReadPricing"  Height="43" >

                <TextBlock Text="Read internal Pricing File" TextWrapping="Wrap" TextAlignment="Center"/>

      </Button>

Datagrid:

<DataGrid VerticalAlignment="Top" HorizontalAlignment="Left" 

                  SelectedItem="{Binding SelectedProduct}"

                  ItemsSource="{Binding View}" AutoGenerateColumns="False" 

                  CanUserAddRows="False" ScrollViewer.VerticalScrollBarVisibility="Visible" 

                  Margin="0,2,0,0"   

                  Height="{Binding RelativeSource={RelativeSource AncestorType={x:Type DockPanel}}, Path=ActualHeight}"  >

                    <DataGrid.Columns>

                        <DataGridTextColumn Header="MianProduct" Binding="{Binding Mainproduct}" Width="*" IsReadOnly="True"/>

                        <DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="*" IsReadOnly="True"/>

                        <DataGridTextColumn Header="Price" Binding="{Binding Price}" Width="*" />

                        <!--<DataGridTextColumn Header="Visible" Binding="{Binding Visible}" Width="*" />-->

                        <DataGridTemplateColumn Header="Visible"  Width="100" >

                            <DataGridTemplateColumn.CellTemplate>

                                <DataTemplate>

                                    <CheckBox IsChecked="{Binding Visible, UpdateSourceTrigger=PropertyChanged}" />

                                </DataTemplate>

                            </DataGridTemplateColumn.CellTemplate>

                        </DataGridTemplateColumn>

                        <DataGridTextColumn Header="NameIcon" Binding="{Binding NameIcon}" Width="*" />

                    </DataGrid.Columns>

      </DataGrid>

ViewModel; Relay command, Product class, covertor class:

class ProductPriceViewModel : INotifyPropertyChanged
	{
		
		public ProductPriceViewModel()
		{

		
		}

		public event PropertyChangedEventHandler PropertyChanged;
		public event EventHandler? CanExecuteChanged;

		public void OnPropertyChanged([CallerMemberName] String info = "") =>
			PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(info));

		private bool Filter(object item)
		{
			Product p = item as Product;
			if (p == null) return true;
			var ret = true;
			if (!String.IsNullOrEmpty(MainProductSearch))
				ret = ret && p.Mainproduct.IndexOf(MainProductSearch, StringComparison.OrdinalIgnoreCase) >= 0 ||
				p.Name.IndexOf(MainProductSearch, StringComparison.OrdinalIgnoreCase) >= 0;
			if (!String.IsNullOrEmpty(SizeSearch))
				ret = ret && p.Name.IndexOf(SizeSearch, StringComparison.OrdinalIgnoreCase) >= 0;
			if (!String.IsNullOrEmpty(MediaType))
				ret = ret && p.Name.IndexOf(MediaType, StringComparison.OrdinalIgnoreCase) >= 0;
			if (Visible.HasValue)
				ret = ret && p.Visible.IndexOf(Visible.Value.ToString(), StringComparison.OrdinalIgnoreCase) >= 0;
			return ret;
		}

		private ICollectionView cvs;

		public ICollectionView View
		{
			get { return cvs; }
			set
			{
				cvs = value;
				OnPropertyChanged("View");
			}
		}
		private readonly ICommand command;
		public ICommand Command
		{
			get
			{
				return command;
			}
		}
		
		//private CollectionViewSource cvs = new CollectionViewSource();

		//      public ICollectionView View { get; set; }
		//public ICollectionView View
		//{
		//    get
		//    {
		//        if (cvs.Source == null)
		//        {
		//            cvs.Source = GetProductsPriceListXML();
		//            cvs.View.Filter = Filter;
		//        }
		//        return this.cvs.View;
		//    }
		//}



		public Product SelectedProduct { get; set; }

		private string _MainProductSearch;
		public string MainProductSearch
		{
			get { return _MainProductSearch; }
			set
			{
				_MainProductSearch = value;
				OnPropertyChanged();
				View.Refresh();
			}
		}

		private string _SizeSearch;
		public string SizeSearch
		{
			get { return _SizeSearch; }
			set
			{
				_SizeSearch = value;
				OnPropertyChanged();
				View.Refresh();
			}
		}

		private string _MediaType;
		public string MediaType
		{
			get { return _MediaType; }
			set
			{
				_MediaType = value;
				OnPropertyChanged();
				View.Refresh();
			}
		}

		private bool? _Visible;
		public bool? Visible
		{
			get { return this._Visible; }
			set
			{
				this._Visible = value;
				OnPropertyChanged();
				View.Refresh();
			}
		}


		public ICommand MyCommand { get => new RelayCommand(executemethod, canexecutemethod); }

		public ICommand ReadCommand { get => new RelayCommand(Execute, canexecutemethod); }


		string pricinglocalfile = @"C:\xmltest\Prices_2022_12_15_All_CM_V4.txt";


        private void Execute(object parm)
        {
			var fe = (FrameworkElement)parm;
			Items = GetProductsPriceListXML();
			View = CollectionViewSource.GetDefaultView(Items);
			View.Refresh();

		}


		private void executemethod(object parameter)
		{
			switch (parameter.ToString())
			{
				case "ExcelExport":
					ExcelUtlity obj = new ExcelUtlity();
					System.Data.DataTable dt = ConvertToDataTable(GetProductsPriceListXML());
					string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + "Price_" + DateTime.Now.ToString("yyyyMMddHHmm") + ".xlsx";
					obj.WriteDataTableToExcel(dt, path);
					System.Windows.MessageBox.Show("Excel Pricing File created on the desktop");
					return;
				
				case "SaveFile":
					data.Save("xxx.txt");
					return;
				case "Reset":
					MainProductSearch = string.Empty;
					SizeSearch = string.Empty;
					SizeSearch = string.Empty;
					Visible = null;
					MediaType = string.Empty;
					break;
				default:
					MediaType = parameter.ToString();
					break;
			}
			View.Refresh();
		}

		private static bool canexecutemethod(object obj) => true;


		

		XElement data;

		private List<Product> GetProductsPriceListXML()
		{
			var mylist = new List<Product>();

			data = XElement.Load(pricinglocalfile);
			foreach (XElement xe1 in data.Elements())
				if (xe1.Name == "Products")
					foreach (var xe2 in xe1.Elements()) mylist.Add(new Product(xe2));
			return mylist;
		}

		

	}



	public class MediaConverter : IValueConverter
	{
		public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
			=> value != null && parameter != null && value.ToString() == parameter.ToString();
		public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
			=> parameter;

	}
	
	public class Product
	{
		public Product(XElement xe3) => this.xe4 = xe3;
		private XElement xe4;
		public string Mainproduct { get => xe4.Name.LocalName; }
		public string Name { get => xe4.Attribute("Name").Value; }
		public string Price
		{
			get
			{
				XElement xe5 = xe4.Descendants("ProductPrice").FirstOrDefault();
				if (xe5 == null) return string.Empty;
				return xe5.Attribute("Price").Value;
			}
			set
			{
				XElement xe5 = xe4.Descendants("ProductPrice").FirstOrDefault();
				if (xe5 != null) xe5.Attribute("Price").Value = value;
			}
		}
		public string Visible
		{
			get
			{
				XElement xe5 = xe4.Descendants("ProductVisibility").FirstOrDefault();
				if (xe5 == null) return string.Empty;
				return xe5.Attribute("Visible").Value;
			}
			set
			{
				XElement xe5 = xe4.Descendants("ProductVisibility").FirstOrDefault();
				if (xe5 != null) xe5.Attribute("Visible").Value = value;
			}
		}
		public string NameIcon
		{
			get
			{
				XAttribute xe5 = xe4.Attribute("DefaultIconName");
				return (xe5 == null) ? string.Empty : xe5.Value;
			}
			set
			{
				XAttribute xe5 = xe4.Attribute("DefaultIconName");
				if (xe5 == null) xe4.Add(new XAttribute("DefaultIconName", value));
				else xe5.Value = value;
			}
		}

	
	}

	public class RelayCommand : ICommand
	{
		private readonly Predicate<object> _canExecute;
		private readonly Action<object> _action;
		public RelayCommand(Action<object> action, Predicate<object> canExecute) { _action = action; _canExecute = canExecute; }
		public void Execute(object o) => _action(o);
		public bool CanExecute(object o) => _canExecute == null ? true : _canExecute(o);
		public event EventHandler CanExecuteChanged
		{
			add { CommandManager.RequerySuggested += value; }
			remove { CommandManager.RequerySuggested -= value; }
		}
	}
Developer technologies | Windows Presentation Foundation
Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
0 comments No comments
{count} votes

Answer accepted by question author
  1. Hui Liu-MSFT 48,711 Reputation points Microsoft External Staff
    2023-01-17T08:25:04.0233333+00:00

    I update your code as follows, you could refer to it. Because I don't know your data content, I return the customized set data instead of the data in the file. I also used my RelayCommand class.

    using System;
    using System.Collections.ObjectModel;
    using System.ComponentModel;
    using System.Runtime.CompilerServices;
    using System.Windows;
    using System.Windows.Data;
    using System.Windows.Input;
    using System.Xml.Linq;
    
    namespace LoadCollectionViewButtonBinding
    {
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }
        }
    
        class ProductPriceViewModel : INotifyPropertyChanged
        {
    
            private ICollectionView icv;
    
            public ICollectionView View
            {
                get { return icv; }
                set
                {
                    icv = value;
                    OnPropertyChanged("View");
                }
            }
            private Product selectedProduct;
    
            public Product SelectedProduct
            {
                get { return selectedProduct; }
                set
                {
                    selectedProduct = value;
                    OnPropertyChanged("SelectedProduct");
                }
            }
    
            public ObservableCollection<Product> Items { get; set; }
            private void Execute(object parm) 
            {
                var fe = (FrameworkElement)parm;
              //  var cvs = (CollectionViewSource)fe.FindResource("cvs");
                Items = GetProductsPriceListXML();
                View = CollectionViewSource.GetDefaultView(Items);
                View.Refresh();
            }
          
            private ObservableCollection<Product> GetProductsPriceListXML()
            {
                var mylist = new ObservableCollection<Product>();
                mylist.Add(new Product() { Name = "jack" });
                mylist.Add(new Product() { Name = "john" });
                mylist.Add(new Product() { Name = "marry" });
                mylist.Add(new Product() { Name = "jenny" });
                //data = XElement.Load(pricinglocalfile);
                //foreach (XElement xe1 in data.Elements())
                //    if (xe1.Name == "Products")
                //        foreach (var xe2 in xe1.Elements()) mylist.Add(new Product(xe2));
                return mylist;
            }
    
            private readonly ICommand command;
            public ICommand Command
            {
                get
                {
                    return command;
                }
            }
            public ProductPriceViewModel()
            {
                command = new RelayCommand(Execute);
              
            }
    
            public event PropertyChangedEventHandler PropertyChanged;
            protected void OnPropertyChanged([CallerMemberName] string name = null)
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
            }
        }
        public class Product
        {
    
            public int Id { get; set; }
            public string Name { get; set; }
            public string Price { get; set; }
        }
    
        public class RelayCommand : ICommand
        {
            private readonly Action<object> _execute;
            private readonly Predicate<object> _canExecute;
    
            public RelayCommand(Action<object> execute)
                : this(execute, null)
            {
            }
    
            public RelayCommand(Action<object> execute, Predicate<object> canExecute)
            {
                if (execute == null)
                    throw new ArgumentNullException("execute");
                _execute = execute;
                _canExecute = canExecute;
            }
    
            public bool CanExecute(object parameter)
            {
                return _canExecute == null ? true : _canExecute(parameter);
            }
    
            public event EventHandler CanExecuteChanged
            {
                add { CommandManager.RequerySuggested += value; }
                remove { CommandManager.RequerySuggested -= value; }
            }
    
            public void Execute(object parameter)
            {
                _execute(parameter);
            }
        }
       
    }
    
    

    The result:

    2

    -

    If the response is helpful, please click "Accept Answer" and upvote it. Note: Please follow the steps in our [documentation][5] to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.