C# 在组合框中显示默认值而不显示集合名称(WPF)
我有C# 在组合框中显示默认值而不显示集合名称(WPF),c#,wpf,combobox,default,default-value,C#,Wpf,Combobox,Default,Default Value,我有组合框: <ComboBox ItemsSource="{Binding Path=MonthDaysList}" IsSynchronizedWithCurrentItem="True"/> ObservableCollection和Binding工作正常,但未在ComobBox中显示默认/第一项: <ComboBox ItemsSource="{Binding Path=MonthDaysList}" IsSynchronizedWithCurrentItem="Tr
组合框
:
<ComboBox ItemsSource="{Binding Path=MonthDaysList}" IsSynchronizedWithCurrentItem="True"/>
ObservableCollection和Binding工作正常,但未在ComobBox
中显示默认/第一项:
<ComboBox ItemsSource="{Binding Path=MonthDaysList}" IsSynchronizedWithCurrentItem="True"/>
可以在视图模型中定义
字符串源属性,并将组合框的SelectedItem
属性绑定到此属性,而不使用设置组合框的名称来解析:
<ComboBox ItemsSource="{Binding Path=MonthDaysList}" SelectedItem="{Binding SelectedMonthDay}"/>
如果要选择第一个值,请将SelectedIndex属性设置为0?或者在视图模型中定义一个字符串源属性,并将组合框的SelectedItem属性绑定到此属性。已尝试,但当Im重新加载MonthDaysList时,它不会刷新要选择的值是什么?只需首先……MonthDaysList每次都会重新加载并正常工作,但它并没有将默认/第一项设置到cbI中,可能需要在您的代码@mm8中进行一些更改,因为我使用[AddNotifyPropertyChangedInterface],但感谢您提供的提示如何完成我的代码只是一个示例。当然,您可以根据自己的要求对其进行任意编辑。但这不是问题的一部分。确切地说,正如我正在学习的那样,在示例中进行更改对我来说是一个很好的实践
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));
}
}