Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind a user control stack panel to an observable collection in WPF

Tags:

c#

wpf

xaml

I am trying to create a contact list user control with a stack panel bound to an ObservableCollection of LoggedInUser

User Control:

<UserControl.Content>
    <Grid>
        <Border BorderBrush="LightBlue" BorderThickness="1,1,1,1" CornerRadius="8,8,8,8" Height="350" HorizontalAlignment="Left" VerticalAlignment="Top" Width="290">
            <ItemsControl x:Name="tStack" Grid.Column="0">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <StackPanel Orientation="Horizontal"/>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <Button Height="30" Content="{Binding Username}"/>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </Border>
    </Grid>
</UserControl.Content>

User Control Code Behind

public partial class ContactList : UserControl
{
    public ContactList()
    {
        InitializeComponent();

        ContactListViewModel clvm = ContactListViewModel.GetInstance();

        clvm.Contacts.Add(new LoggedInUser("test", "123"));

        this.DataContext = clvm.Contacts;
    }
}

And my ContactListViewModel

class ContactListViewModel
{
    private static ContactListViewModel instance;

    public ObservableCollection<LoggedInUser> Contacts = new ObservableCollection<LoggedInUser>();

    public static ContactListViewModel GetInstance() 
    {
        if (instance == null)
            instance = new ContactListViewModel();

        return instance;
    }
}

LoggedInUser class, just in case

public class LoggedInUser
{
    private string username;
    public string Username
    {
        get { return username; }
        set { username = value; }
    }
}

My stack panel remains empty! Help!

like image 716
Julien Avatar asked Jul 26 '12 18:07

Julien


1 Answers

You have not bound the ItemsSource of your ItemsControl, so it effectively has no data. Your data context is the collection, so you need only do this:

<ItemsControl ItemsSource="{Binding}" ...

Alternatively, if you instead set your data context to the view model instance (as is customary for MVVM), you would do this:

<ItemsControl ItemsSource="{Binding Contacts}" ...
like image 73
Kent Boogaart Avatar answered Oct 18 '22 03:10

Kent Boogaart