【发布时间】:2013-08-29 02:54:30
【问题描述】:
我在 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属性设置一个默认值;
但它们都不起作用,第一个元素总是空的。有人可以帮忙吗?
【问题讨论】:
-
您是否尝试过将 selectedvalue 而不是 selecteditem 绑定到 SelectedId 并通过 vm 设置 SelectedId?
-
@dnr3,不能提供更多细节吗?如何在vm中设置SelectedId
-
我的意思是你在你的 vm 中创建另一个名为 SelectedId 的属性来绑定到 ComboBox 的 SelectedValue,因为组合框的 SelectedItem 可能不是你要找的那个(该值可能是一个 ComboBoxItem而不是 City 的实例)
-
别在意我的最后一条评论,我刚刚检查过,我还可以将 SelectedItem 绑定到 SelectedCity 并且效果很好,您是如何设置 selectedCity 默认值的?
-
@dnr3,我将 Cities 的第一个元素分配给构造函数中的 SelectedCity 属性
标签: wpf data-binding mvvm combobox