2017-11-29 7 views
0

하위 범주가있는 범주 클래스가 있으며 하위 범주에 하위 범주가있을 수 있습니다. 각 노드에 대해 클릭 명령을 사용하여 계층 적 트리에 대한 데이터 바인딩을 만들고 싶습니다.MVVM을 사용하여 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>