【发布时间】:2012-01-13 15:18:29
【问题描述】:
我正在尝试实现一个解决方案,该解决方案将在通过文本框和添加按钮添加项目后在列表框中显示项目......作为 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" 工作...非常感谢!!