使用MVVM将WPF树绑定到一对多对象

时间:2017-11-29 18:21:59

标签: c# wpf mvvm

我有一个类别类,它有子类别,子类别可能有子类别,依此类推。我想为每个节点的click命令创建一个分层树的数据绑定。

这是我的班级。

public partial class ProductCategory
{
    [Key]
    public int ProductCategoryId { get; set; }
    [Required]
    public string Description { get; set; }

    #region Foreign Keys
    public ProductCategory ParentProductCategory { get; set; }
    public int? ParentProductCategoryId { get; set; }
    public ICollection<ProductCategory> ChildProductCategories { get; set; }
    #endregion
    public virtual ICollection<ProductType> ProductTypes { get; set; }
}

1 个答案:

答案 0 :(得分:0)

这就是我解决问题的方法......

代码背后(查看模型)

public class ProductCategoryViewModel : ViewModelBase
{
    private ObservableCollection<ProductCategory> _productCategories;

    public ObservableCollection<ProductCategory> ProductCategories
    {
        get => _productCategories;
        set => Set(ref _productCategories, value);
    }
    public RelayCommand<string> ClickCategoryCommand { get; set; }

    public ProductCategoryViewModel()
    {
        _productCategories = new ObservableCollection<ProductCategory>();
        var p1 = new ProductCategory()
        {
            Description = "P1",
            ChildProductCategories = new List<ProductCategory>()
            {
                new ProductCategory()
                {
                    Description = "C1",
                    ChildProductCategories = new List<ProductCategory>()
                    {
                        new ProductCategory()
                        {
                            Description = "C1 C1"
                        },
                        new ProductCategory()
                        {
                            Description = "C1 C2"
                        }
                    }
                },
                new ProductCategory()
                {
                    Description = "C2"
                }
            }
        };
        _productCategories.Add(p1);
        ClickCategoryCommand = new RelayCommand<string>(Click);
    }

    private void Click(string description)
    {
        MessageBox.Show(description);
    }
}

Xaml代码

  <TreeView ItemsSource="{Binding ProductCategories}">
        <TreeView.Resources>
            <HierarchicalDataTemplate DataType="{x:Type local:ProductCategory}" ItemsSource="{Binding ChildProductCategories}">
                <Button Content="{Binding Path=Description}" 
                           Command="{Binding DataContext.ClickCategoryCommand, RelativeSource={RelativeSource AncestorType={x:Type TreeView}}}"
                        CommandParameter="{Binding Description}"/>
            </HierarchicalDataTemplate>
        </TreeView.Resources>
    </TreeView>