填充ListBox

时间:2012-01-11 07:32:01

标签: c# wpf

我有一个带有文本框和提交按钮的窗口。按下提交按钮时,文本框中的数据应填充到列表框中并保存。

这样做的最佳方法是什么?我尝试了一个推荐(使用ObservableCollection)从我之前的一个问题,但我似乎无法让它工作。我试过像这样实现它:

我创建了一个类:

public class AccountCollection
{
    private string accountName;
    public string AccountName
    {
        get { return accountName; }
        set { accountName = value; }
    }
    public AccountCollection(string accountName)
    {
        AccountName = accountName;
    }
}        

在我的XAML中分配了绑定:

<ListBox ItemsSource="{Binding AccountName, Mode=TwoWay}" IsSynchronizedWithCurrentItem="True" Height="164" HorizontalAlignment="Left" Margin="12" Name="accountListBox" VerticalAlignment="Top" Width="161" SelectionChanged="accountListBox_SelectionChanged" />

...最后,当用户点击另一个包含“提交”按钮和文本框的窗口中的提交按钮时:

private void okBtn_Click(object sender, RoutedEventArgs e)
{
    BindingExpression expression = okBtn.GetBindingExpression(accountaddTextBox.Text);
    expression.UpdateSource();
}

但是,唉,我无处可去。我在GetBindingExpression部分收到错误消息:

参数1:无法从'string'转换为'System.Windows.DependencyProperty'

这里显而易见的是,当我创建课程时,我没有在文本框中指定任何有关帐户名称的内容,所以我甚至不知道该课程是否正确。

我基本上很困惑,不知道该怎么做。任何帮助将不胜感激......

3 个答案:

答案 0 :(得分:2)

这是一个使用MVVM方法的演示

视图模型

public class AccountListViewModel : INotifyPropertyChanged
{

    ICommand AddAccountCommand {get; set;}

    public AccountListViewModel()
    {
        AccountList = new ObservableCollection<string>();
        AddAccountCommand= new RelayCommand(AddAccount);
        //Fill account List saved data
        FillAccountList();
    }

    public AddAccount(object obj)
    {
        AccountList.Add(AccountName); 
        //Call you Model function To Save you lIst to DB or XML or Where you Like
        SaveAccountList()   
    }

    public ObservableCollection<string> AccountList 
    { 
            get {return accountList} ; 
            set
            {
                accountList= value
                OnPropertyChanged("AccountList");
            } 
    }

    public string AccountName 
    { 
            get {return accountName } ; 
            set
            {
                accountName = value
                OnPropertyChanged("AccountName");
            } 
    }

}

Xaml Binding

<ListBox ItemsSource="{Binding Path=AccountList}" Height="164" HorizontalAlignment="Left" Margin="12" Name="accountListBox" VerticalAlignment="Top" Width="161" />

<TextBox Text={Binding Path=AccountName}></TextBox>
<Button Command={Binding Path=AddAccountCommand}><Button>

Xaml.cs代码

    # region Constructor

    /// <summary>
    /// Default Constructor
    /// </summary>
    public MainView()
    {
        InitializeComponent();
        this.DataContext = new AccountListViewModel();
    }

    # endregion

INotifyPropertyChanged的实施和形成的遗产由你决定

答案 1 :(得分:2)

模型

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

ListBox XAML

 <ListBox Name="MyAccounts" DisplayMemberPath="AccountName" />

代码背后

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

编辑:在listbox xaml上添加了displaymemberpath

答案 2 :(得分:1)

您的ListBox的ItemsSource是AccountName,它只是一个字符串,但不是一个集合。

您需要创建一个viewmodel(视图的datacontext),如下所示:

public class ViewModel
{
    public ViewModel()
    {
        Accounts = new ObservableCollection<string>();
    }

    public ObservableCollection<string> Accounts { get; set; }
}

将ItemsSource绑定到Accounts属性:

<ListBox ItemsSource="{Binding Accounts}" Height="164" HorizontalAlignment="Left" Margin="12" Name="accountListBox" VerticalAlignment="Top" Width="161" />

然后,在按钮的单击事件处理程序中,您可以简单地将文本框的当前值添加到集合中:

private void okBtn_Click(object sender, RoutedEventArgs e)
{
    Accounts.Add(accountaddTextBox.Text);
}

但是不要忘记将窗口的DataContext设置为ViewModel类。