Search code examples
wpfxamlbindingdatacontext

multi Datacontext wpf


Who can explain to me how to use two different datacontext ?

this is my file.xaml.cs :

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        DataContext = new string[] { "Female", "Male", "Animal", "Safe", "Soft", "Hard", "Space", "Landscape", "Outside", "Inside",
        "City", "France", "Flower", "Sunset", "Sky", "Fireworks", "Spring", "Winter", "Summer", "Fall", "Christmas", "Halloween",
        "Ghost", "Demon", "Angel", "Watermelon", "Storm", "Waterfall", "Night", "Sun","Moon", "Dog", "Cat", "Food", "Cheese",
        "Kancolle", "IT", "UFO", "Travel", "Sport", "Nightmare"};
   } 

and here my file.xaml :

<ScrollViewer HorizontalAlignment="Left" Height="170" VerticalAlignment="Top" Width="97" Margin="10,149,0,0">
        <ListBox ItemsSource="{Binding .}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <CheckBox Content="{Binding Path=.}" />
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </ScrollViewer>

Everything work well here, but i would like add an second ScrollViewer exactly like the first one, but with another content. so the datacontexte need to be different for each of them.

thank you for giving me a little of your time.


Solution

  • You don't need to set different DataContexts.

    Create two collection properties in your MainWindow class and set the DataContext to the window instance.

    public IEnumerable<string> Collection1 { get; }
    public IEnumerable<string> Collection2 { get; }
    
    public MainWindow()
    {
        InitializeComponent();
    
        Collection1 = new string[] { ... }; 
        Collection2 = new string[] { ... }; 
        DataContext = this;
    }
    

    Bind the ListBox's ItemSource to the collection properties:

    <ListBox ItemsSource="{Binding Collection1}" ...>
    ...
    <ListBox ItemsSource="{Binding Collection2}" ...>