【问题标题】:Why the first item of my ComboBox always empty为什么我的 ComboBox 的第一项总是空的
【发布时间】: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


【解决方案1】:

您应该在构造函数中构造城市列表,然后将 selectedCity 分配给列表的第一个值

public CityListViewModel()
{
    cities = City.GetDefaultCities();
    selectedCity = cities[0];
}

然后您只需在 Cities 属性 getter 中返回已填写的城市列表

public List<City> Cities
{
   get { return cities; }
   set { cities = value; }
}

【讨论】:

    猜你喜欢
    • 2011-11-08
    • 2013-10-16
    • 1970-01-01
    • 2013-03-15
    • 1970-01-01
    • 2020-07-20
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多