wpf 将项目从文本框添加到列表框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15201821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add Item to ListBox from TextBox
提问by MTA
I have this ListBox:
我有这个ListBox:
<ListBox x:Name="PlaylistList" AlternationCount="2" SelectionChanged="DidChangeSelection">
<ListBox.GroupStyle>
<GroupStyle />
</ListBox.GroupStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And i want to add option to add new item to the ListBox. And i want to do it by adding a TextBoxto the ListBoxwhen the user press a Button and then the user press enter and add the text in the TextBoxto the ListBox.
我想添加选项以将新项目添加到ListBox. 我想通过在用户按下按钮时添加 aTextBox来实现ListBox,然后用户按下 Enter 并将文本添加TextBox到ListBox.
I try to add text box to the listbox but i can add only one type of ListBox.ItemTemplate, how can i handle it?
我尝试将文本框添加到列表框,但我只能添加一种类型ListBox.ItemTemplate,我该如何处理?
采纳答案by Eugene Pavlov
Updatedto add textbox inside Listbox:
更新以在列表框内添加文本框:
To add new item into ListBox, in Button Click code-behind do:
要将新项目添加到 ListBox,请在 Button Click 代码隐藏中执行以下操作:
TextBox TextBoxItem = new TextBox();
// set TextBoxItem properties here
PlaylistList.Items.Add(TextBoxItem);
回答by Eugene Pavlov
Write this code when your button is clicked so that the textbox text will be added to the listbox.
单击按钮时编写此代码,以便将文本框文本添加到列表框。
private void addEventButton_Click(object sender, EventArgs e)
{
// Adds events to listbox.
if (this.titleTextBox.Text != "")
{
listBox1.Items.Add(this.titleTextBox.Text);
listBox2.Items.Add(this.titleTextBox.Text);
this.titleTextBox.Focus();
this.titleTextBox.Clear();
}
}
回答by J.Starkl
Your ListBox:
您的列表框:
<ListBox
Name="MyListBox"
ItemsSource="{Binding Path=Reason}"
DisplayMemberPath="Description"/>
Make a ObversableCollection for the Items of the ListBox
为 ListBox 的项目创建 ObversableCollection
public ObservableCollection<IdObject> items
{
get { return (ObservableCollection<IdObject>)GetValue(ApplicationsProperty); }
set { SetValue(ApplicationsProperty, value); }
}
items = new ObservableCollection<IdObject>();
My ID-Object in this case has the following properties:
在这种情况下,我的 ID-Object 具有以下属性:
private int _id = 0;
private string _description = "";
Bind the collection to the ListBox:
将集合绑定到 ListBox:
MyListBox.ItemsSource = items;
Then make a TextBox with a Button, and an event for pressing the button, where you add the text to the observable collection:
然后创建一个带有 Button 的 TextBox 和一个用于按下按钮的事件,您可以在其中将文本添加到 observable 集合中:
items.Add(new IdObject(someId, TextBox.Text));
The ListBox will update, when the ObservableCollection is changed
当 ObservableCollection 更改时,ListBox 将更新

