2017-11-29 7 views
0

サブカテゴリを持つカテゴリクラスがあり、サブカテゴリにサブカテゴリなどがある可能性があります。私は各ノードのクリックコマンドで階層ツリーのデータバインディングを作成したいと思います。MVVMを使用して1対多のオブジェクトにWPFツリーをバインドする

これは私のクラスです。

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; } 
} 
+0

です? – Fruchtzwerg

+0

@Fruchtzwergどのようにバインディングを作成するのですか?類似のトピックが見つかりましたが、決定的な数と子オブジェクトのタイプについて説明します。 –

+0

@Fruchtzwergここでは関係は1対多であり、親オブジェクトは子供と同じ型ですので、いくつかの再帰の必要性があるかもしれません。 –

答えて

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> 
関連する問題