Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default value in WPF ComboBox

Tags:

c#

.net

wpf

I am using ComboBox ItemsSource property binding to display items from a List to combo box.

Following is the code:

<ComboBox x:Name="Cmb_Tax" ItemsSource="{Binding TaxList}" 
            DisplayMemberPath="ChargeName" SelectedItem="{Binding 
            SelectedTax,UpdateSourceTrigger=PropertyChanged}" IsEditable="True" 
            IsTextSearchEnabled="True" SelectionChanged="Cmb_Tax_SelectionChanged"/>

Classes.Charges _selected_tax = new Classes.Charges();
public Classes.Charges SelectedTax
{
    get
    {
        return _selected_tax;
    }
    set
    {
        _selected_tax = value;
    }
}

List<Classes.Charges> _taxlist = new List<Classes.Charges>();
public List<Classes.Charges> TaxList
{
    get
    {
        return _taxlist;
    }
    set
    {
        _taxlist = value;
        OnPropertyChanged("TaxList");
    }
}

It displays the items in the combo box correctly.

There is a particular item in TaxList "No Tax" which I want to be selected by default in the combo box. This item can be present at any index in the list (Not necessary first or last item of the list).

I am trying to use the following code to set the selected index property of combo box, but sadly its not working.

TaxList = Classes.Charges.GetChargeList("Tax");
Cmb_Tax.DataContext = this;            
int i = TaxList.FindIndex(x => x.ChargeName == tax_name);
Cmb_Tax.SelectedIndex = i;

The Method FindIndex() returns the index of the "No Tax" correctly but when I try assigning it to SelectedIndex of combo the SelectedIndex doesn't change. It stays at -1.

Update1

private void Cmb_Tax_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    MessageBox.Show(SelectedTax.ChargeName);
}

Update2 Updated the code as per suggested by @ElectricRouge

<ComboBox x:Name="Cmb_Tax" ItemsSource="{Binding TaxList, Mode=TwoWay}" 
                      DisplayMemberPath="ChargeName" SelectedItem="{Binding SelectedTax,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}"
                      IsEditable="True" IsTextSearchEnabled="True" 
                      SelectionChanged="Cmb_Tax_SelectionChanged"/>


Classes.Charges _selected_tax = new Classes.Charges();
        public Classes.Charges SelectedTax
        {
            get
            {
                return _selected_tax;
            }
            set
            {
                _selected_tax = value;
                OnPropertyChanged("SelectedTax");
            }
        }

        ObservableCollection<Classes.Charges> _taxlist = new ObservableCollection<Classes.Charges>();
        public ObservableCollection<Classes.Charges> TaxList
        {
            get
            {
                return _taxlist;
            }
            set
            {
                _taxlist = value;
                OnPropertyChanged("TaxList");
            }
        }

public void Load_Tax(string tax_name = null, Classes.Charges selected_tax = null)
        {
            TaxList = Classes.Charges.GetParticularChargeList("Tax");
            Cmb_Tax.DataContext = this;
            //Cmb_Tax.SelectedValue = tax_name;
            SelectedTax = selected_tax;
            //int i = TaxList.FindIndex(x => x.ChargeName == tax_name);
            //Cmb_Tax.SelectedIndex = i;
        }

Any idea why this must be happening? Also please suggest any other approach to display default in combo box.

like image 425
Nilesh Barai Avatar asked Oct 21 '22 15:10

Nilesh Barai


1 Answers

Here's a working sample:

Viewmodel:

 public MainWindow()
    {
        InitializeComponent();

        var vm = new ViewModel();
        this.DataContext = vm;
        this.Loaded += (o,e) => vm.LoadData();
    }

    public class ViewModel : INotifyPropertyChanged
    {
        private IList<Charges> taxList;
        public ICollectionView TaxList { get; private set; }

        public void LoadData()
        {                
            taxList = Charges.GetChargeList("taxes");

            TaxList = CollectionViewSource.GetDefaultView(taxList);
            RaisePropertyChanged("TaxList");

            TaxList.CurrentChanged += TaxList_CurrentChanged;              

            var noTax = taxList.FirstOrDefault(c => c.ChargeName == "No Tax");
            TaxList.MoveCurrentTo(noTax);
        }

        void TaxList_CurrentChanged(object sender, EventArgs e)
        {
            var currentCharge = TaxList.CurrentItem as Charges;
            if(currentCharge != null)
                MessageBox.Show(currentCharge.ChargeName);
        }



        public event PropertyChangedEventHandler PropertyChanged;
        public void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

View:

<ComboBox x:Name="cboTaxList" 
              ItemsSource="{Binding TaxList}" 
              DisplayMemberPath="ChargeName"
              IsSynchronizedWithCurrentItem="True" />
like image 124
Lorentz Vedeler Avatar answered Nov 03 '22 01:11

Lorentz Vedeler