none
Send collection to Command parameter

    Question

  • I am doing command binding with button. It's working fine but when I try to add a new object through bound command. One of my property comming from GUI becomes null when it fires. If I try to add CommandParameter then it always return null. The property which I want to send through CommandParameter contain all hierarchies of objects and collections. Guide me please how should I bind this type of property? It ll be really appreciated.
    Sunday, April 15, 2012 3:56 AM

Answers

  • Hi maifs,

    Could you share me with the command codes and the xaml?

    As you mentioned , you want to send a collection, could you show me the detail of the collection?

    If the collection is in the viewmodel , instead of sending it , you can read it directly in your viewmodel.

    If the collection isn't in the viewmodel , you can set it as param as the code below:

           
     <ListBox Name="listBox">
            </ListBox>
            <Button Content="Load" Width="120"     
                    Command="{Binding DemoCommand}"     
                    CommandParameter="{Binding ElementName=listBox, Path=ItemsSource}" />
            
    public MainPage()
            {
                InitializeComponent();
                IList<string> strList = new List<string> { "0", "1", "2" };
                listBox.ItemsSource = strList;
            }

     

    public class MainViewModel : ViewModelBase
        {
            public ICommand DemoCommand { get; set; }
            public MainViewModel()
            {
                DemoCommand = new DelegateCommand(CanLoadDemos, LoadDemos);
            }
            private void LoadDemos(object param)
            {
                return;
            }
            private bool CanLoadDemos(object param)
            {
                return true;
            }
        }
    
        public class DelegateCommand : ICommand
        {
            public event EventHandler CanExecuteChanged;
    
            Func<object, bool> _canExecute = null;
            Action<object> _executeAction = null;
    
            public DelegateCommand(Func<object, bool> canExecute, Action<object> executeAction)
            {
                _canExecute = canExecute;
                _executeAction = executeAction;
            }
            public bool CanExecute(object parameter)
            {
                if (_canExecute != null)
                    return _canExecute(parameter);
                return true;
            }
    
            public void UpdateCanExecuteState()
            {
                if (CanExecuteChanged != null)
                    CanExecuteChanged(this, new EventArgs());
            }
    
            public void Execute(object parameter)
            {
                if (_executeAction != null)
                    _executeAction(parameter);
                UpdateCanExecuteState();
            }
        }

    Please put breakpoint to the LoadDemos method, and you can see the list is there.

    Monday, April 16, 2012 10:28 PM
  • Hi,

    what is the type ProposalManager?

    Could you show me the object definition?

    and more ,Could you set a BreakPoint to the xaml,to see whether it bind fine.

    (Or just change the binding to a IList Collect to see whether it bind fine)

    Friday, April 27, 2012 5:08 AM
  • <ns:Button x:Name="btnAdd" Content="Add" Style="{StaticResource
    ButtonLeftMarginStyle}" Command="{Binding InsuranceAddCommand,Source={StaticResource
    AssetInsurance}}" CommandParameter="{Binding ProposalManager}" />


    And the CommandParameter="{Binding ProposalManager} is binding to a Class name ,not a created
    object. Maybe you should bind to Controller.
            private ProposalManager _proposalManager;
           
    private ProposalManager Controller
           
    {
               
    get
               
    {
                   
    if (_proposalManager == null)
                        _proposalManager
    = GetController<ProposalManager>(this);
                   
    return _proposalManager;
               
    }
           
    }
    And in the code , there are two private key words.
    
    
    Friday, April 27, 2012 5:22 AM

All replies

  • Hi maifs,

    Could you share me with the command codes and the xaml?

    As you mentioned , you want to send a collection, could you show me the detail of the collection?

    If the collection is in the viewmodel , instead of sending it , you can read it directly in your viewmodel.

    If the collection isn't in the viewmodel , you can set it as param as the code below:

           
     <ListBox Name="listBox">
            </ListBox>
            <Button Content="Load" Width="120"     
                    Command="{Binding DemoCommand}"     
                    CommandParameter="{Binding ElementName=listBox, Path=ItemsSource}" />
            
    public MainPage()
            {
                InitializeComponent();
                IList<string> strList = new List<string> { "0", "1", "2" };
                listBox.ItemsSource = strList;
            }

     

    public class MainViewModel : ViewModelBase
        {
            public ICommand DemoCommand { get; set; }
            public MainViewModel()
            {
                DemoCommand = new DelegateCommand(CanLoadDemos, LoadDemos);
            }
            private void LoadDemos(object param)
            {
                return;
            }
            private bool CanLoadDemos(object param)
            {
                return true;
            }
        }
    
        public class DelegateCommand : ICommand
        {
            public event EventHandler CanExecuteChanged;
    
            Func<object, bool> _canExecute = null;
            Action<object> _executeAction = null;
    
            public DelegateCommand(Func<object, bool> canExecute, Action<object> executeAction)
            {
                _canExecute = canExecute;
                _executeAction = executeAction;
            }
            public bool CanExecute(object parameter)
            {
                if (_canExecute != null)
                    return _canExecute(parameter);
                return true;
            }
    
            public void UpdateCanExecuteState()
            {
                if (CanExecuteChanged != null)
                    CanExecuteChanged(this, new EventArgs());
            }
    
            public void Execute(object parameter)
            {
                if (_executeAction != null)
                    _executeAction(parameter);
                UpdateCanExecuteState();
            }
        }

    Please put breakpoint to the LoadDemos method, and you can see the list is there.

    Monday, April 16, 2012 10:28 PM
  • Otomi thanks for guiding. I 'll share my xaml tomorrow ASAP and sorry for late reply because I couldn't see the reply of my post. Yes it is not a part of view model that's why I want to send it through command parameter. It contains more than 7 to 9 hundred collections( in some case collection of collections.) I ll try according to your provided solution tomorrow But Otomi I could't get you that how could I bind CommandParameter with this type of collection if I don't use any control as you mentioned .
    Tuesday, April 17, 2012 1:25 PM
  • Hi maifs,

    Could you share the collection datatype of your data?

    Maybe you should change the datatype in order to send it to the command parameter.

    Tuesday, April 17, 2012 9:17 PM
  • Hi Otomii.

    Sorry if i am doing in some wrong way:

     

     

    DataType is ProposalManager and its contain too many collection itself.
    
    =====================ucInsurance.cs================================
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Animation;
    using System.Windows.Shapes;
    using NetSol.Silverlight.Core;
    using NFS.UI.Silverlight.ServiceClient;
    using System.Collections.ObjectModel;
    using NFS.UI.Silverlight.ServiceClient.ProposalProxy;
    using Lookup = NFS.UI.Silverlight.ServiceClient.LookupProxy;
    using NFS.UI.Silverlight.ViewModels;
    using NetSol.Web.Controls.Silverlight;
    
    namespace NFS.UI.Silverlight.UserControls
    {
        public partial class ucInsurance : Popup
        {
            #region Constructor
    
            public ucInsurance()
            {
                InitializeComponent();
                PostInitialize();
                viewModel = new InsuranceViewModel();
                
            }
    
            #endregion
    
            #region Properties
    
            private ProposalManager _proposalManager;
            private ProposalManager Controller
            {
                get
                {
                    if (_proposalManager == null)
                        _proposalManager = GetController<ProposalManager>(this);
                    return _proposalManager;
                }
            }
    
            private InsuranceViewModel viewModel;
    
            #endregion
    
            #region Get/Set Data
    
            protected override bool SetData()
            {            
                SetData(Controller.Helper.AssetIndex);
                return true;
            }
    
            protected override bool SetData(int index)
            {
                viewModel = new InsuranceViewModel() { Controller = Controller};
    
                if (viewModel.Controller == null)
                    viewModel.Controller = Controller;
    
    	    SyncBinding();
    
                return true;
            }
    
            #endregion
    
    
    	private void SyncBinding()
            {
                if (viewModel.AssetExist())
                {
                    gvInsuranceDetails.ItemsSource = viewModel.Controller.DataContext.ASSET
                        .Current<AssetEntity>()[Controller.Helper.AssetIndex].PROPOSALASSETINSURANCE.Current<PRPLASETINSRInfo>();
                }
            }     
              
          
        }
    }
    
    
    =======================ucInsurance.xaml=========================== 
    
    	<nfs:Popup x:Class="NFS.UI.Silverlight.UserControls.ucInsurance"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:nfs="clr-namespace:NetSol.Silverlight.Core;assembly=NetSol.Silverlight.Core"
        xmlns:ns="clr-namespace:NetSol.Web.Controls.Silverlight;assembly=NetSol.Web.Controls.Silverlight"
        xmlns:ctrl="clr-namespace:NFS.UI.Silverlight.Controls"
        xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
        xmlns:uc="clr-namespace:NFS.UI.Silverlight.UserControls"
        xmlns:viewModel="clr-namespace:NFS.UI.Silverlight.ViewModels"
        xmlns:toolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit"                   
        mc:Ignorable="d" Header="Insurance Details"
        d:DesignHeight="200" d:DesignWidth="1250" Height="400" Width="1250" >
        <toolkit:BusyIndicator>
            <Grid x:Name="LayoutRoot" Style="{StaticResource GridStyle}">
                <Grid.Resources>
                    <viewModel:InsuranceViewModel x:Key="AssetInsurance" />
                </Grid.Resources>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="*" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="25" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition />
                </Grid.ColumnDefinitions>
                <ctrl:ValidationMessages x:Name="validator" Grid.Row="0"/>
    
                <ns:GridView x:Name="gvInsuranceDetails"  Style="{StaticResource GridViewCommonStyle}" Grid.Row="1">
                    <ns:GridView.Columns>                   
                        <ns:GridViewDataColumn IsFilterable="False" Width="100"  MinWidth="100">
                            <ns:GridViewDataColumn.Header>
                                <ns:Label  HorizontalAlignment="Center" HorizontalContentAlignment="Right" Content ="Financed" />
                            </ns:GridViewDataColumn.Header>
                            <ns:GridViewDataColumn.CellTemplate>
                                <DataTemplate>
                                    <ns:CheckBox IsChecked="{Binding FINANCEDIND,Mode=TwoWay}" HorizontalAlignment="Center" />
                                </DataTemplate>
                            </ns:GridViewDataColumn.CellTemplate>                                        
                    </ns:GridView.Columns>
                </ns:GridView>
                <StackPanel Grid.Row="3" Style="{StaticResource StackPanelHorizontalLeftToRightStyle}">                
                    <ns:Button x:Name="btnAdd" Content="Add"  Style="{StaticResource ButtonLeftMarginStyle}"  
                    Command="{Binding InsuranceAddCommand,Source={StaticResource AssetInsurance}}" CommandParameter="{Binding ProposalManager}"  />               
                </StackPanel>
            </Grid>
        </toolkit:BusyIndicator>
    </nfs:Popup>
    
    ===========================================InsuranceViewModel =======================
    
    
     public class InsuranceViewModel : ViewModelBase
        {
            #region Constructors
    
            public InsuranceViewModel()
            {            
    
            }
    
            public InsuranceViewModel(ProposalManager controller)
                : this()
            {
                m_controller = controller;
            }
    
            #endregion
    
            #region Properties
            private ProposalManager m_controller;
            public ProposalManager Controller
            {
                set
                {
                    m_controller = value;
                }
                get
                {
                    if (m_controller != null)
                        return m_controller;
                    return null;
                }
    
            }
           
    
            #endregion       
    
    
            public void AddProposalAssetInsurance()
            {
                int seqID = 0;
                if (AssetExist())
                {
                    ObservableCollection<PRPLASETINSRInfo> proposalInsurance = Controller.DataContext.ASSET.Current<AssetEntity>()[Controller.Helper.AssetIndex].
                            PROPOSALASSETINSURANCE.Current<PRPLASETINSRInfo>();
    
                    if (proposalInsurance.Count > 0)
                    {
                        seqID = proposalInsurance.Select(s => s.INSRSEQID).Max() + 1;
                    }
                    else
                    {
                        seqID = 1;
                    }
    
                    PRPLASETINSRInfo proposalAssetInsurance = new PRPLASETINSRInfo()
                    {
                        RowState = DataRowState.Added,
                        INSRSEQID = seqID,
                        SESSIONID = SessionBean.UserSessionObject.User.SessionId,
                        SESSIONCDE = SessionBean.UserSessionObject.User.SessionCode
                    };
    
                    Controller.DataContext.ASSET[Controller.Helper.AssetIndex].PROPOSALASSETINSURANCE.Add(proposalAssetInsurance);
                }
            }
    
           
    
            #endregion
    
            private ICommand _insuranceAddCommand;
            public ICommand InsuranceAddCommand
            {
                get
                {
                    if (_insuranceAddCommand == null)
                        _insuranceAddCommand = new DelegateCommand(OnInsuranceAddCommandExecuted);
                    return _insuranceAddCommand;
                }
            }
            private void OnInsuranceAddCommandExecuted(object parameter)
            {           
    		Controller = (ProposalManager)parameter;	
    	 	AddProposalAssetInsurance()
            }
    
        }
    
    
    
    Wednesday, April 18, 2012 3:59 AM
  • Hi otomi. See Above mentioned source please and let me know in case of any confusion.
    Wednesday, April 18, 2012 4:42 AM
  • Hi,

    I've had a marry leave these days.

    I will try your code as soon as possible.

    Sunday, April 22, 2012 11:10 PM
  • Hi otomi congratulations :) No problem , you can take time as much as you can.
    Monday, April 23, 2012 2:21 PM
  • Hi,

    what is the type ProposalManager?

    Could you show me the object definition?

    and more ,Could you set a BreakPoint to the xaml,to see whether it bind fine.

    (Or just change the binding to a IList Collect to see whether it bind fine)

    Friday, April 27, 2012 5:08 AM
  • <ns:Button x:Name="btnAdd" Content="Add" Style="{StaticResource
    ButtonLeftMarginStyle}" Command="{Binding InsuranceAddCommand,Source={StaticResource
    AssetInsurance}}" CommandParameter="{Binding ProposalManager}" />


    And the CommandParameter="{Binding ProposalManager} is binding to a Class name ,not a created
    object. Maybe you should bind to Controller.
            private ProposalManager _proposalManager;
           
    private ProposalManager Controller
           
    {
               
    get
               
    {
                   
    if (_proposalManager == null)
                        _proposalManager
    = GetController<ProposalManager>(this);
                   
    return _proposalManager;
               
    }
           
    }
    And in the code , there are two private key words.
    
    
    Friday, April 27, 2012 5:22 AM
  • Hi Otomi. I tried with both Controller as well as ProposalManager but I received controller null each time. Yes it's private but Otomi should it have some impacts if we set a controller property of viewModel in our GUI and pass it. Then why is it getting null value? It works fine when I directly call the required method of ViewModel and in case of using Command controller becomes Null.
    Tuesday, May 01, 2012 1:37 PM