Bind user control stack panel to monitored collection in WPF

I'm trying to create a custom contact list item with a stack LoggedInUser tied to an ObservableCollection 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> 

Custom control code

 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 , just in case

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

My stack panel remains blank! Help!

+6
source share
1 answer

You did not bind ItemsSource to ItemsControl , so it has no data. The data context is a collection, so you only need to do this:

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

Alternatively, if you instead set your data context to an instance of the view model (as is usually the case with MVVM), you will do the following:

 <ItemsControl ItemsSource="{Binding Contacts}" ... 
+7
source

Source: https://habr.com/ru/post/921425/


All Articles