2013-12-17 32 views
4

我希望名爲LstbClients的ListBox在每個Label或TextBlock中顯示名稱和電話號碼(對我無關緊要),我之前用ComboBox DataBinded並且工作正常很好,但由於某種原因,它不適用於此ListBox。列表框不顯示特定對象的值(數據綁定)

這是XAML代碼。

<ListBox x:Name="lstbClients" 
     Height="300" 
     Grid.Row="0" Grid.Column="0" 
     Style="{StaticResource inputControls}" 
     ItemsSource="{Binding clients}"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <StackPanel Orientation="Horizontal"> 
       <Label Content="{Binding Name}"/> 
       <Label Content=", "/> 
       <Label Content="{Binding Phonenumber}"/> 
      </StackPanel> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

這是後面的代碼:

//clients is a filled ObservableCollection<client> 
lstbClients.ItemsSource = clients; 

這背後Client.cs

public class Client 
{ 
    public int ID; 
    public string Lastname; 
    public string Name; 
    public string Streetname; 
    public string Postcode; 
    public string City; 
    public int Phonenumber; 
    public string Email; 
    public DateTime CreationDate; 
    public DateTime BirthDate; 

    public Client(int id, string lastname, string name, DateTime birthDate, string streetname, string postcode, string city, int phonenumber, string email, DateTime creationDate) 
    { 
     this.ID = id; 
     this.Lastname = lastname; 
     this.Name = name; 
     this.Streetname = streetname; 
     this.Postcode = postcode; 
     this.City = city; 
     this.Phonenumber = phonenumber; 
     this.Email = email; 
     this.CreationDate = creationDate; 
     this.BirthDate = birthDate; 
    } 
} 

代碼對於一些奇怪的原因,列表框的標籤也只顯示」, 「並忽略名稱和電話號碼,是的當我」打開「ListBox與我的最終WPF應用程序,所有的數據都包含...因此,ListBox獲取的數據,但它只是不想顯示它的標籤lstbClients,所以我無法確定哪個標籤包含哪些數據。

+0

顯示客戶端類的代碼。你爲什麼要從XAML和後面的代碼中設置ItemsSource? –

+5

歡迎來到本站!沒有必要在你的問題中添加「對不起,我是初學者」 - 每個人都是初學者,所以不用擔心。祝你的項目好運! – dasblinkenlight

+0

你的XAML看起來不錯,我猜你還沒有在你的Observable Collection上實現'INotifyPropertyChanged'。請顯示Observable Collection聲明的代碼。另外,在運行時檢查你的輸出窗口,以確保你沒有得到綁定錯誤。這些可以幫助你找到你的問題。 –

回答

3

綁定工作與屬性,而不是字段。

更改字段屬性是這樣的:

public string Name {get; set;} 
public int Phonenumber {get; set;} 

在一個旁註,你應該在的情況下實現INotifyPropertyChanged你的類,你要GUI要刷新的任何財產上的變化。請參閱此處以供參考 - How to implement Property change notification

+0

謝謝!這有效,但我始終認爲,當你不把邏輯放在它裏面時,get和set是沒有必要的......但是看起來我錯了。無論如何,感謝這個答案,我也將更多地瞭解INotifyPropertyChanged –

+0

這些是自動屬性。編譯器會在幕後爲你自動創建備份字段。 –

相關問題