Question

I know similar questions like this have been asked before but I'm really having a hard time getting this to work. I have a Dictionary defined as:

Dictionary<string, List<DataClass>> MyDict = new Dictionary<string, List<DataClass>>();
//Add some code to populate the dictionary here...

public class DataClass
{
   public string Name {get; set;}
   public int Age {get; set;}
   public int ID {get; set;}
}

My XAML is, basically:

<StackPanel...>
   <Expander...>
      <ListBox.../>
   </Expander>
   <Expander...>
      <ListBox.../>
   </Expander>
   ...
</StackPanel>

My questions are: 1) How do I make the number of Expander/ListBoxs appear to match the string value in MyDict. Meaning, I want one Expander/ListBox pair for each Key in MyDict with the Header of Expander equal to the Key. 2) How do I get the Value of MyDict to populate the ListBox? I already have my code written for the list box and it works for a List but I don't know how to pull it out of a Dictionary.

I'm trying to do this correctly with WPF but I may write the dynamic loading of controls in the codebehind. Just thought I would ask before going that route.

Thank you!

Était-ce utile?

La solution

You can use ItemsControl (msdn) and specify ItemTemplate:

<ItemsControl ItemsSource="{Binding}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Expander Header="{Binding Key}">
                <ListBox ItemsSource="{Binding Value}">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <TextBlock Text="{Binding ID}" />
                                <TextBlock Text="{Binding Name}" />
                                <TextBlock Text="{Binding Age}" />
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
            </Expander>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top