将用户控件堆栈面板绑定到WPF中的可观察集合

Jul*_*ien 6 c# wpf xaml

我试图创建绑定到一个堆叠面板联系人列表的用户控制ObservableCollectionLoggedInUser

用户控制:

<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>
Run Code Online (Sandbox Code Playgroud)

用户控制代码背后

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

        ContactListViewModel clvm = ContactListViewModel.GetInstance();

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

        this.DataContext = clvm.Contacts;
    }
}
Run Code Online (Sandbox Code Playgroud)

还有我的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;
    }
}
Run Code Online (Sandbox Code Playgroud)

LoggedInUser 上课,以防万一

public class LoggedInUser
{
    private string username;
    public string Username
    {
        get { return username; }
        set { username = value; }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的堆栈面板仍然是空的!救命!

Ken*_*art 7

你没有绑定ItemsSource你的ItemsControl,所以它实际上没有数据.您的数据上下文是集合,因此您只需执行以下操作:

<ItemsControl ItemsSource="{Binding}" ...
Run Code Online (Sandbox Code Playgroud)

或者,如果您将数据上下文设置为视图模型实例(按照MVVM的惯例),您可以这样做:

<ItemsControl ItemsSource="{Binding Contacts}" ...
Run Code Online (Sandbox Code Playgroud)