在WPF ComboBox中设置默认值
我正在使用ComboBox ItemsSource属性绑定来显示从List到combobox的项目。
以下是代码:
Classes.Charges _selected_tax = new Classes.Charges(); public Classes.Charges SelectedTax { get { return _selected_tax; } set { _selected_tax = value; } } List _taxlist = new List(); public List TaxList { get { return _taxlist; } set { _taxlist = value; OnPropertyChanged("TaxList"); } }
它正确显示combobox中的项目。
TaxList "No Tax"
有一个特定项目,我想在combobox中默认选择它。 此项目可以出现在列表中的任何索引处(不必是列表中的第一个或最后一个项目)。
我试图使用以下代码来设置combobox的选定索引属性,但遗憾的是它无法正常工作。
TaxList = Classes.Charges.GetChargeList("Tax"); Cmb_Tax.DataContext = this; int i = TaxList.FindIndex(x => x.ChargeName == tax_name); Cmb_Tax.SelectedIndex = i;
方法FindIndex()正确返回"No Tax"
的索引,但是当我尝试将其分配给组合的SelectedIndex
不会更改。 它保持在-1。
UPDATE1
private void Cmb_Tax_SelectionChanged(object sender, SelectionChangedEventArgs e) { MessageBox.Show(SelectedTax.ChargeName); }
Update2根据@ElectricRouge的建议更新了代码
Classes.Charges _selected_tax = new Classes.Charges(); public Classes.Charges SelectedTax { get { return _selected_tax; } set { _selected_tax = value; OnPropertyChanged("SelectedTax"); } } ObservableCollection _taxlist = new ObservableCollection(); public ObservableCollection 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; }
知道为什么会这样吗? 另外,请建议在combobox中显示默认值的任何其他方法。
这是一个工作样本:
视图模型:
public MainWindow() { InitializeComponent(); var vm = new ViewModel(); this.DataContext = vm; this.Loaded += (o,e) => vm.LoadData(); } public class ViewModel : INotifyPropertyChanged { private IList 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)); } } } }
视图:
List没有实现INotifyCollectionChanged
使其成为ObservableCollection
ObservableCollection _taxlist = new ObservableCollection(); public ObservableCollection TaxList { get { return _taxlist; } set { _taxlist = value; OnPropertyChanged("TaxList"); } }
并尝试设置Mode = TwoWay
SelectedItem="{Binding SelectedTax,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}"