首页 > 解决方案 > 当代码在运行时更新时,将 Observable 集合绑定到组合框有效。但是在再次构建解决方案后它不起作用

问题描述

我正在尝试将 an 绑定ÒbservableCollectionComboBoxusing MVVM

这是模型:

 public class ItemModel
    {
        public string Name{ get; set; }
    }

视图模型:

public class ItemsViewModel : INotifyPropertyChanged
{
    public ObservableCollection<ItemModel> ObsItems{ get; set; }
    public ItemsViewModel ()
    {       
        List<string> items=MyDataTable.AsEnumerable().Select(row => row.Field<string>
        ("Id")).Distinct().ToList();

        ObsItems= new ObservableCollection<ItemModel>();

        foreach (var item in items)
        {
            ObsItems.Add(
                new ItemModel
                {
                    Name = item
                }
                );
        }

    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void RaisePropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

看法:

<ComboBox HorizontalAlignment="Left" Margin="65,85,0,0" VerticalAlignment="Top" Width="120" 
ItemsSource="{Binding ObsItems}">
                <ComboBox.DataContext>
                    <Models:ItemsViewModel />
                </ComboBox.DataContext>
                <ComboBox.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Name}"/>
                    </DataTemplate>
                </ComboBox.ItemTemplate>
            </ComboBox>

从头开始构建时,此代码不起作用。但它在运行时工作,当视图代码 (xaml) 被修改时。一旦程序退出并再次运行,它就会停止工作。我错过了什么?

标签: c#wpfmvvmbindingobservablecollection

解决方案


您应该使用只读的 ObservableCollection 属性:

public class ItemsViewModel
{
    public ObservableCollection<ItemModel> Items { get; } 
        = new ObservableCollection<ItemModel>();

    public void InitializeItems()
    {
        Items.Clear();

        foreach (var item in MyDataTable
            .AsEnumerable()
            .Select(row => row.Field<string>("Id"))
            .Distinct()
            .Select(name => new ItemModel { Name = name }))
        {
            Items.Add(item);
        }
    }
}

推荐阅读