代码之家  ›  专栏  ›  技术社区  ›  4est

在组合框中显示默认值而不显示集合名称(WPF)

  •  0
  • 4est  · 技术社区  · 6 年前

    我有 ComboBox :

    <ComboBox ItemsSource="{Binding Path=MonthDaysList}" IsSynchronizedWithCurrentItem="True"/>
    

    MonthDaysList 数据:

    public ObservableCollection<string> MonthDaysList { get; internal set; }
    public void GetMonths() {
       MonthDaysList = new ObservableCollection<string>();
       foreach (var item in MyConceptItems) {
                MonthDaysList.Add(item.DateColumn);
       }}
    

    ComobBox

    enter image description here

    without 设置的名称 ?

    1 回复  |  直到 6 年前
        1
  •  1
  •   mm8    6 年前

    定义 string 视图模型中的源属性并绑定 SelectedItem 财产 ComboBox

    <ComboBox ItemsSource="{Binding Path=MonthDaysList}" SelectedItem="{Binding SelectedMonthDay}"/>
    

    确保你实现了 INotifyPropertyChanged

    public class ViewModel : INotifyPropertyChanged
    {
        private ObservableCollection<string> _monthDaysList;
        public ObservableCollection<string> MonthDaysList
        {
            get { return _monthDaysList; }
            internal set { _monthDaysList = value; OnPropertyChanged(); }
        }
    
    
        private string _selectedMonthDay;
        public string SelectedMonthDay
        {
            get { return _selectedMonthDay; }
            internal set { _selectedMonthDay = value; OnPropertyChanged(); }
        }
    
        public void GetMonths()
        {
            MonthDaysList = new ObservableCollection<string>();
            if (MyConceptItems != null && MyConceptItems.Any())
            {
                foreach (var item in MyConceptItems)
                {
                    MonthDaysList.Add(item.DateColumn);
                }
                SelectedMonthDay = MonthDaysList[0];
            }
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged([CallerMemberName] String propertyName = "")
        {
            if (PropertyChanged != null)
                PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }