在没有设置NAME(WPF)的情况下将默认值显示在ComboBox中

问题描述 投票:0回答:1

我有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);
   }}

ObservableCollection和Binding工作正常,但它没有在ComobBox中显示默认/第一项:

enter image description here

有可能解决它without设置ComboBox的名字?

c# wpf combobox default default-value
1个回答
1
投票

在视图模型中定义string源属性,并将SelectedItemComboBox属性绑定到此属性:

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

如果要动态设置source属性,请确保实现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));
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.