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

6

我将尝试创建一个联系人列表用户控件,其中一个堆栈面板绑定到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; }
    }
}

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

你是在使用WPF还是Silverlight? - Bernard
我只问了6个问题,从未得到满意的答案。也许这会是一个!另外,编辑问题以提到WPF。 - Julien
1
你还没有将ItemsControl的ItemsSource属性绑定到你的viewModel的Contact属性上。请这样做,然后用this.DataContext = clvm;代替this.DataContext = clvm.Contacts; - Dante
1个回答

7
您还没有绑定您的ItemsControlItemsSource,因此它实际上没有数据。您的数据上下文是集合,所以您只需要这样做:
<ItemsControl ItemsSource="{Binding}" ...

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接