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!
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}" ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With