c# - 将用户控件堆栈面板绑定(bind)到 WPF 中的可观察集合

标签 c# wpf xaml

我正在尝试创建一个联系人列表用户控件,其中堆栈面板绑定(bind)到 LoggedInUserObservableCollection

用户控制:

<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>

背后的用户控制代码

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

        ContactListViewModel clvm = ContactListViewModel.GetInstance();

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

        this.DataContext = clvm.Contacts;
    }
}

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

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

我的堆栈面板仍然是空的!帮助!

最佳答案

您还没有绑定(bind) ItemsControlItemsSource,因此它实际上没有数据。您的数据上下文是集合,因此您只需执行以下操作:

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

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

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

关于c# - 将用户控件堆栈面板绑定(bind)到 WPF 中的可观察集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11675511/

相关文章:

c# - WPF Dockpanel 超出父级的宽度

c# - 如何在 Windows 8 中创建大于屏幕的 View

c# - 用于 .NET/C# 编程的最佳等效 VisualStudio IDE for Mac

wpf - wpf数据网格中的绑定(bind)组合框

c# - 在 C# 中,为什么我在声明它时看到我的 int 变量中存储了一个零,但仍然收到一条错误消息说我应该初始化它?

wpf - Grid/ScrollViewer - 卡住网格标题行垂直滚动,但不卡住水平滚动

wpf - WPF UserControl上的依赖注入(inject)(Windsor)

c# - 自定义 WPF/XAML Canvas

c# - 登录不区分大小写

c# - 为什么我们从接口(interface)而不是类创建对象实例?