2012-07-26 81 views
6

我試圖創建勢必ObservableCollectionLoggedInUser綁定用戶控件棧面板可觀察集合在WPF

的用戶控件棧面板的聯繫人列表中的用戶控件:

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

我堆棧面板仍然是空的!幫幫我!

+0

你使用的是WPF還是Silverlight? – Bernard 2012-07-26 18:19:00

+0

我只問了6個問題,從來沒有得到滿意的答案。也許這將是一個!另外,編輯提到WPF的問題。 – Julien 2012-07-26 18:21:49

+1

您還沒有將ItemsControl的ItemsSource屬性綁定到viewModel的Contact屬性。做到這一點,然後代替'this.DataContext = clvm.Contacts;'寫出'this.DataContext = clvm; ' – Dante 2012-07-26 18:28:27

回答

7

您沒有限制您的ItemsControlItemsSource,因此它實際上沒有數據。你的數據上下文是收藏,所以你只需要做到這一點:

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

另外,如果你不是設置您的數據上下文視圖模型實例(如通常用於MVVM),你可以這樣做:

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