简体   繁体   English

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

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

I am trying to create a contact list user control with a stack panel bound to an ObservableCollection of LoggedInUser 我正在尝试创建一个联系人列表用户控件,其堆栈面板绑定到LoggedInUserObservableCollection

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 还有我的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 LoggedInUser类,以防万一

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. 您尚未绑定ItemsControlItemsSource ,因此它实际上没有数据。 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: 或者,如果您将数据上下文设置为视图模型实例(按照MVVM的惯例),您可以这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM