我已经在stackoverflow和MSDN中搜索了很长时间,我不确定为什么标记的答案适用于其他人但对我不起作用。
我有像这样的城市课程
public class City
{
public int Id { get; set; }
public string Name { get; set; }
public static List<City> GetDefaultCities()
{
List<City> cities = new List<City>();
cities.Add(new City { Id = 1, Name = "New York" });
cities.Add(new City { Id = 2, Name = "Chicago" });
cities.Add(new City { Id = 3, Name = "Miami" });
cities.Add(new City { Id = 4, Name = "Houston" });
cities.Add(new City { Id = 5, Name = "Dallas" });
return cities;
}
}
我的ViewModel中的属性:
private List<City> cities;
public List<City> Cities
{
get { return City.GetDefaultCities(); }
set { cities = value; }
}
private City selectedCity;
public City SelectedCity
{
get { return selectedCity; }
set
{
if (selectedCity != value)
{
selectedCity = value;
RaisePropertyChanged("SelectedCity");
}
}
}
我视图中的XAML
<ComboBox ItemsSource="{Binding Cities}" Width="100" Height="30"
DisplayMemberPath="Name"
SelectedValuePath="Id"
SelectedItem="{Binding SelectedCity}"
/>
我尝试了3个解决方案: 1.在XAML中将SelectedIndex设置为0; 2.将Text Property设置为XAML中Cities Name的第一个元素; 3.在ViewModel中为City属性设置默认值;
但是所有这些都不起作用,第一个元素总是空的。有人可以帮忙吗?
答案 0 :(得分:0)
您应该在构造函数中构造城市列表,然后为selectedCity分配列表的第一个值
public CityListViewModel()
{
cities = City.GetDefaultCities();
selectedCity = cities[0];
}
然后您只需返回Cities属性getter中已填充的城市列表
public List<City> Cities
{
get { return cities; }
set { cities = value; }
}