2011-06-22 36 views
1

我正在嘗試做一個預算程序。我需要在裏面放置文本框列表的groupbox。與WPF和C嵌套數據綁定#

<ItemsControl DataContext="{Binding}"> 
    <ItemsControl.ItemTemplate> 
    <DataTemplate> 
     <GroupBox Header="{Binding}"> 
     <ItemsControl DataContext="{Binding}"> 
      <ItemsControl.ItemTemplate> 
      <DataTemplate> 
       <StackPanel Orientation="Horizontal"> 
       <TextBlock Text="{Binding Text}" /> 
       <TextBlock Text="{Binding Value}" /> 
       </StackPanel> 
      </DataTemplate> 
      </ItemsControl.ItemTemplate> 
     </ItemsControl> 
     </GroupBox> 
    </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 

我需要某種方式與groupboxes數據綁定列表(也許?),所以我想創建的組框列表,裏面有些線將與貨幣值的文本。所以我可以創建一個名爲「公寓」的小組,有兩行「Rent $ 3000」和「Maintenance $ 150」。然後我可以有一個名爲「Car」的第二組,例如「Insurance」,「Loan」和「Maintenance」。

但是,我會怎樣綁定這個?我將如何在C#中執行此操作。我很茫然。

+1

你爲什麼不創建一個模型來組織你的數據更像你正在尋找的,然後創建一個你可以更容易地綁定到的模板? – Jay

回答

5

建立在Jay的評論之外,你會想創建一個Hierarchical數據模型。請注意我已經留在性能執行INotifyPropertyChanged的你

public class BudgetLineItem : INotifyPropertyChanged 
{ 
    public string Name { get; set; } 
    public decimal Cost { get; set; } 
} 

public class BudgetGroup : INotifyPropertyChanged 
{ 
    public string GroupName { get; set; } 
    public ObservableCollection<BudgetLineItem> LineItems { get; set; } 
} 

public class BudgetViewModel : INotifyPropertyChanged 
{ 
    public ObservableCollection<BudgetGroup> BudgetGroups { get; set; } 
} 

那麼你的數據的模板應該是這樣的:

<ItemsControl DataContext="{Binding ViewModel}" 
       ItemsSource="{Binding BudgetGroups}"> 
    <ItemsControl.ItemTemplate> 
    <DataTemplate> 
     <GroupBox Header="{Binding GroupName}"> 
     <ItemsControl ItemsSource="{Binding LineItems}"> 
      <ItemsControl.ItemTemplate> 
      <DataTemplate> 
       <StackPanel Orientation="Horizontal"> 
       <TextBlock Text="{Binding Name}" /> 
       <TextBlock Text="{Binding Cost}" /> 
       </StackPanel> 
      </DataTemplate> 
      </ItemsControl.ItemTemplate> 
     </ItemsControl> 
     </GroupBox> 
    </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 
0

我可以在這裏是關閉基地,但它聽起來像是你想改變DataTemplate基於從異類對象列表中綁定的對象的類型。

如果是這種情況,您希望查看DataTemplateSelectors或爲您想要在列表中支持的每種類型創建DataTemplates。

例如,對於一個公寓,你可能有:

<DataTemplate DataType="local:ApartmentBudget"> 
    <StackPanel Orientation="Horizontal"> 
    <TextBlock Text="{Binding Text}" /> 
    <TextBlock Text="{Binding Value}" /> 
    </StackPanel> 
</DataTemplate> 

一個汽車可能看起來像:

<DataTemplate DataType="local:CarBudget"> 
    <StackPanel Orientation="Horizontal"> 
    <TextBlock Text="{Binding Insurance}" /> 
    <TextBlock Text="{Binding Loan}" /> 
    <TextBlock Text="{Binding Maintenance}" /> 
    </StackPanel> 
</DataTemplate> 

那麼你的ItemsControl可以這樣設置:

<ItemsControl ItemSource="{Binding BudgetItems}"> 

的將根據數據類型挑選正確的DataTemplate。您可以通過創建自定義DataTemplateSelector來進行更多的控制。

查看https://msdn.microsoft.com/en-us/library/ms742521(v=vs.100).aspx瞭解更多信息。