2013-11-19 3 views
0

Я новичок в WPF, и я пытаюсь связать вложенную коллекцию.Устранение неполадок вложенных коллекций

Я нашел много тем в Интернете о привязке, и я пробовал следовать за this question/answer. Я попытался изменить значения Datacontext и ItemSource, но я просто не могу понять это правильно.

XAML:

<UserControl x:Class="WpfApplication1.Nav1" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     mc:Ignorable="d" 
     d:DesignHeight="620" d:DesignWidth="950"> 
<Grid Background="#FF741125"> 
    <TextBlock Height="61" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBlock1" Text="BEVERAGES" VerticalAlignment="Top" Width="250" FontSize="20" FontWeight="Black" /> 
    <ItemsControl x:Name="Stack" DataContext="{Binding myMenu}" ItemsSource="{Binding Subs}" BorderThickness="0" Margin="0,60,0,0"> 
     <ItemsControl.ItemTemplate> 
      <DataTemplate> 
       <StackPanel> 
        <Label Content="{Binding Name}" FontWeight="Bold" /> 
        <ItemsControl ItemsSource="{Binding Nodes}" BorderThickness="0" Margin="0,60,0,0"> 
         <ItemsControl.ItemTemplate> 
          <DataTemplate> 
           <Grid Height="60" Width="900"> 
            <Grid.Background> 
             <ImageBrush ImageSource="/WpfApplication1;component/Images/MenuGrid.fw.png" /> 
            </Grid.Background> 
            <Grid.RowDefinitions> 
             <RowDefinition Height="10" /> 
             <RowDefinition Height="10" /> 
             <RowDefinition Height="10" /> 
             <RowDefinition Height="10" /> 
             <RowDefinition Height="10" /> 
             <RowDefinition Height="10" /> 
            </Grid.RowDefinitions> 
            <Grid.ColumnDefinitions> 
             <ColumnDefinition Width="50" /> 
             <ColumnDefinition Width="50" /> 
             <ColumnDefinition Width="50" /> 
             <ColumnDefinition Width="50" /> 
             <ColumnDefinition Width="50" /> 
             <ColumnDefinition Width="50" /> 
             <ColumnDefinition Width="50" /> 
             <ColumnDefinition Width="50" /> 
             <ColumnDefinition Width="50" /> 
             <ColumnDefinition Width="50" /> 
             <ColumnDefinition Width="50" /> 
             <ColumnDefinition Width="50" /> 
             <ColumnDefinition Width="50" /> 
             <ColumnDefinition Width="50" /> 
             <ColumnDefinition Width="50" /> 
             <ColumnDefinition Width="50" /> 
             <ColumnDefinition Width="50" /> 
             <ColumnDefinition Width="50" /> 
            </Grid.ColumnDefinitions> 

            <Label Content="{Binding Name}" Grid.Column="0" Grid.Row="0" Grid.RowSpan="3" Grid.ColumnSpan="14" FontWeight="Bold" /> 
            <Label Content="{Binding Description}" Grid.Column="1" Grid.Row="2" Grid.RowSpan="3" Grid.ColumnSpan="14" /> 
            <Label Content="{Binding Cost}" ContentStringFormat="{}${0}" Grid.Column="16" Grid.Row="0" Grid.RowSpan="5" Grid.ColumnSpan="2" /> 

           </Grid> 

          </DataTemplate> 
         </ItemsControl.ItemTemplate> 
        </ItemsControl> 
       </StackPanel> 
      </DataTemplate> 
     </ItemsControl.ItemTemplate> 
    </ItemsControl> 

</Grid> 

Класс:

public class Menu 
{ 
    public ObservableCollection<Category> Subs; 

    public Menu() 
    { 
     Subs = new ObservableCollection<Category>(); 
    } 
} 

public class Category 
{ 
    public ObservableCollection<MenuItem> Nodes; 
    public Category() 
    { 
     Nodes = new ObservableCollection<MenuItem>(); 
    } 
    private string name; 
    public string Name 
    { 
     get { return this.name; } 
     set { this.name = value; } 
    } 
    public Category(string name) 
    { 
     this.name = name; 
     Nodes = new ObservableCollection<MenuItem>(); 
    } 
} 

public class MenuItem 
{ 
    public MenuItem() 
    { 
    } 

    public MenuItem(string name, string description, double cost) 
    { 
     this.itemName = name; 
     this.description = description; 
     this.cost = cost; 
    } 

    private string itemName; 
    public string ItemName 
    { 
     get { return this.itemName; } 
     set { this.itemName = value; } 
    } 

    private string description; 
    public string Description 
    { 
     get { return this.description; } 
     set { this.description = value; } 
    } 

    private double cost; 
    public double Cost 
    { 
     get { return this.cost; } 
     set { this.cost = value; } 
    } 
} 

CS:.

public Nav1() 
    { 
     InitializeComponent(); 
     // Init Model 
     Menu myMenu = new Menu(); 
     myMenu.Subs.Add(new Category("Soft Drinks")); 
     myMenu.Subs.Add(new Category("Coffee")); 
     myMenu.Subs.Add(new Category("Premium")); 

     myMenu.Subs[0].Nodes.Add(new MenuItem("Pepsi", "Cool & Refreshing", 1.39)); 
     myMenu.Subs[0].Nodes.Add(new MenuItem("Diet Pepsi", "Cool & Refreshing", 1.39)); 
     myMenu.Subs[0].Nodes.Add(new MenuItem("7Up", "Cool & Refreshing", 1.39)); 
     myMenu.Subs[0].Nodes.Add(new MenuItem("Mug Root Beer", "Cool & Refreshing", 1.39)); 
     myMenu.Subs[0].Nodes.Add(new MenuItem("Brisk Iced Tea", "Cool & Refreshing", 1.39)); 
     myMenu.Subs[0].Nodes.Add(new MenuItem("Bottled Water", "Thirsty? Aquafina.", 2.75)); 
     // Set DataContext for StackPanel 
     Stack.DataContext = myMenu.Subs; 
    } 

Он отображает имена категорий (например, "Безалкогольные напитки" или «Кофе "), но я не могу отобразить все пункты. Кроме того, есть ли лучшие способы сделать это? Как уже упоминалось, я новичок в WPF, и, похоже, у меня много интересных функций, которые мне не хватает.

Спасибо за чтение!

+0

Вам нужно использовать 'HierarchicalDataTemplate' вместо' DataTemplate'. –

+0

Привет @Bob, это привело меня в правильном направлении! Я переключился на использование 'TreeView' +' HierarchicalDataTemplate', следуя [этому учебнику] (http://blogs.msdn.com/b/mikehillberg/archive/2009/10/30/treeview-and-hierarchicaldatatemplate-step-by- step.aspx). Если бы вы смогли добавить свой комментарий к нему в качестве ответа, я бы хотел пометить его как принятый. Большое спасибо! – eckc

ответ

1

Использование DataTemplate не позволяет использовать вложенные элементы, поскольку оно не предоставляет свойство ItemsSource.

<DataTemplate> 
    <TextBlock Text={Binding MyTextValue}/> 
</DataTemplate> 

Однако, если вы используете HierarchicalDataTemplate, вы можете использовать ItemsSource свойство для определения следующего уровня элементов.

<HierarchicalDataTemplate ItemsSource={Binding MyListOfLevelTwoItems}> 
    <TextBlock Text={Binding MyLevelOneValue}/> 
</HierarchicalDataTemplate> 
<DataTemplate DataType={x:Type MyLevelTwoItem}> 
    <TextBlock Text={Binding MyLevelTwoValue}/> 
</DataTemplate> 
Смежные вопросы