我正在基于代码隐藏绑定 ComboBox,下面是我的 XAML 和代码隐藏:
<Window x:Class="ComboBoxBindingDatabase.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ComboBox Height="29" HorizontalAlignment="Left" Margin="135,60,0,0" Name="comboBox1" VerticalAlignment="Top" Width="194" IsEditable="True"/>
<TextBox Height="39" HorizontalAlignment="Left" Margin="135,159,0,0" Name="textBox1" VerticalAlignment="Top" Width="194" />
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="384,165,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
<TextBox Height="35" HorizontalAlignment="Left" Margin="368,0,0,172" Name="textBox2" VerticalAlignment="Bottom" Width="115" />
</Grid>
和背后的代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
BindComboBox(comboBox1);
}
ArrayList b = new ArrayList();
public void BindComboBox(ComboBox comboBoxName)
{
b.Add("a");
b.Add("b");
b.Add("c");
b.Add("d");
comboBoxName.ItemsSource = b;
comboBoxName.DisplayMemberPath = Name;
comboBoxName.SelectedValuePath = Name;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
b.Add(textBox2.Text);
foreach (string s in b)
{
comboBox1.ItemsSource = b;
comboBox1.DisplayMemberPath = Name;
comboBox1.SelectedValuePath = Name;
}
}
}
因此,当我第一次运行该项目时,ComcoBox 将 a、b、cd 显示为下拉列表。但是当我在文本框中输入一些新字母并单击按钮时,ArrayList b 确实将新字母添加到列表中,我正在尝试重新绑定组合框,但它不起作用。它仍然显示 a,b,c,d 认为我看到 ArrarList b 确实增加了。
为什么 ComboBox 不重新绑定?无论如何,是否可以根据 Code Behind 将元素动态添加到 ComboBox 中,而只是简单的 item.add 方法。
提前致谢。