簡體   English   中英

將用戶控件堆棧面板綁定到WPF中的可觀察集合

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

我正在嘗試創建一個聯系人列表用戶控件,其堆棧面板綁定到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; }
    }
}

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

您尚未綁定ItemsControlItemsSource ,因此它實際上沒有數據。 您的數據上下文是集合,因此您只需執行以下操作:

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

或者,如果您將數據上下文設置為視圖模型實例(按照MVVM的慣例),您可以這樣做:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM