如何在C#的视图内绑定viewmodel中对象的IEnumerable列表

时间:2018-10-10 15:37:53

标签: c# wpf mvvm listbox ienumerable

如何在视图(列表框)中绑定对象的IEnumerable列表?

例如,我有:

  • 拥有IEnumerable功能的Product对象。
  • 用于向产品添加功能的ViewModel ProductViewModel。
  • 该产品的视图,该视图允许执行插入和删除功能以及具有Products.Features的绑定列表框的操作。

问题在于,每次添加功能时,列表框都不会更新。

产品模型

    public class Product : ObservableObject
{
    #region Fields
    string code, name;
    Category category;
    ObservableCollection<Feature> features;
    #endregion

    #region Properties

    public string Code
    {
        get => code;
        set
        {
            if (string.IsNullOrWhiteSpace(value))
                throw new ArgumentNullException(value, "Il codice del prodotto non può essere nullo.");
            if (value.Length > 10)
                throw new ArgumentOutOfRangeException(value, "Il codice del prodotto non può essere lungo più di 10 caratteri.");
            code = value;
            RaisePropertyChangedEvent("Code");
        }
    }

    public string Name
    {
        get => name;
        set
        {
            if (string.IsNullOrWhiteSpace(value))
                throw new ArgumentNullException(value, "Il nome del prodotto non può essere nullo.");
            if (value.Length > 20)
                throw new ArgumentOutOfRangeException(value, "Il nome del prodotto non può essere lungo più di 20 caratteri.");
            name = value;
            RaisePropertyChangedEvent("Name");
        }
    }

    public Category Category
    {
        get => category;
        set
        {
            category = value;
            RaisePropertyChangedEvent("Category");
        }
    }

    public ObservableCollection<Feature> Features
    {
        get => features;
        set
        {
            features = value;
            RaisePropertyChangedEvent("Features");
            RaisePropertyChangedEvent("PrintFeatures");
        }
    }

    public string PrintFeatures
    {
        get
        {
            string line = ""; 
            foreach(var feature in features)
            {
                line += $"{feature.Description}{Environment.NewLine}";
            }
            return line;
        }
    }

    public int HashCode => Code.GetHashCode();

    #endregion
}

ViewModel

public class ProductViewModel : BaseViewModel
{
    #region Fields
    ObservableCollection<Category> categories;
    ObservableCollection<FeatureType> featureTypes;
    #endregion

    #region Data Properties
    public ObservableCollection<Category> Categories
    {
        get => categories;
        set
        {
            categories = value;
            RaisePropertyChangedEvent("Categories");
        }
    }

    public ObservableCollection<FeatureType> FeatureTypes
    {
        get => featureTypes;
        set
        {
            featureTypes = value;
            RaisePropertyChangedEvent("FeatureTypes");
        }
    }

    public Product NewProduct { get; set; }

    public Feature NewFeature { get; set; }

    public Feature SelectedFeature { get; set; }
    #endregion

    #region Commands
    public ICommand AddItem { get; set; }
    public ICommand AddFeature { get; set; }
    #endregion

    #region Constructor
    public ProductViewModel(WarehouseViewModel warehouseViewModel)
    {
        NewFeature = new Feature();
        NewProduct = new Product();

        AddFeature = new AddFeatureCommand(NewProduct.Features, NewFeature);
        AddItem = new AddItemCommand(warehouseViewModel.Products, NewProduct);

        Categories = new ObservableCollection<Category>();
        Categories.Add(new Category { Name = "Infiorescenze" });
        Categories.Add(new Category { Name = "Oli" });

        FeatureTypes = new ObservableCollection<FeatureType>();
        FeatureTypes.Add(new FeatureType
        {
            Name = "Peso",
            UnitMeasure = "grammi",
        });
        FeatureTypes.Add(new FeatureType
        {
            Name = "Pezzi",
            UnitMeasure = "semi",
        });
    }
    #endregion
}

添加功能命令

class AddFeatureCommand : ICommand
{
    #region Fields
    ObservableCollection<Feature> features;
    Feature feature;
    #endregion

    #region Constructor

    public AddFeatureCommand(ObservableCollection<Feature> features, Feature feature)
    {
        this.features = features;
        this.feature = feature;
    }

    #endregion

    #region ICommand Members

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public void Execute(object parameter)
    {
        if (features == null)
            features = new ObservableCollection<Feature>();
        var newFeature = new Feature
        {
            Type = new FeatureType
            {
                Name = feature.Type.Name,
                UnitMeasure = feature.Type.UnitMeasure,
            },
            Value = feature.Value,
        };
        features.Add(newFeature);
    }

    #endregion
}

1 个答案:

答案 0 :(得分:2)

将您的IEnumerable<T>替换为ObservableCollection<T>

无论何时在集合中添加或删除项目,这都会通知任何绑定的控件。