可能重複:
WPF ListBox - Display properties of the ItemSource列表框顯示「Namespace.Accounts」,而不是實際的文本
我想實現一個解決方案添加它們後,將顯示在ListBox項目通過一個文本框和添加按鈕...作爲WPF的新手,我幾乎得到了這個想法(經過了一個星期的頭撞我的桌子...大聲笑)
問題是,列表框是正在填充「WinBudget.Accounts」而不是輸入到列表框中的實際項目。
請幫忙。
模型
// the model is the basic design of an object containing properties
// and methods of that object. This is an account object.
public class Account : INotifyPropertyChanged
{
private string m_AccountName;
public event PropertyChangedEventHandler PropertyChanged;
public string AccountName
{
get { return m_AccountName;}
set
{
m_AccountName = value;
OnPropertyChanged("AccountName");
}
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
列表框XAML
<ListBox Name="MyAccounts" />
後面的代碼
// create a collection of accounts, then whenever the button is clicked,
//create a new account object and add to the collection.
public partial class Window1 : Window
{
private ObservableCollection<Account> AccountList = new ObservableCollection<Account>();
public Window1()
{
InitializeComponent();
AccountList.Add(new Account{ AccountName = "My Account" });
this.MyAccounts.ItemsSource = AccountList;
}
private void okBtn_Click(object sender, RoutedEventArgs e)
{
AccountList.Add(new Account{ AccountName = accountaddTextBox.Text});
}
}
@lance,提到那個線程。 DisplayMemberPath =「AccountName」工作......非常感謝! – Woody 2012-01-13 15:24:36