当在运行时更新代码时,将可观察的集合绑定到组合框即可使用但是在重新构建解决方案后,它不起作用

问题描述

我正在尝试使用ÒbservableCollectionComboBox绑定到MVVM

这是模型:

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

viewmodel:

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" 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)后就可以使用。一旦退出程序,它将停止工作并再次运行。我错过了什么?

解决方法

您应该使用只读的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);
        }
    }
}