我有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
中显示默认/第一项:
有可能解决它without
设置ComboBox
的名字?
在视图模型中定义string
源属性,并将SelectedItem
的ComboBox
属性绑定到此属性:
<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));
}
}