情况 1 - 您没有数据源:
您只需填充ComboBox
静态值如下 -
- 来自 XAML:
<ComboBox Height="23" Name="comboBox1" Width="120">
<ComboBoxItem Content="Alice"/>
<ComboBoxItem Content="Bob"/>
<ComboBoxItem Content="Charlie"/>
</ComboBox>
- 来自代码隐藏 - 1:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
comboBox1.Items.Add("Alice");
comboBox1.Items.Add("Bob");
comboBox1.Items.Add("Charlie");
}
- 来自代码隐藏 - 2:
// insert item at specified index of populated ComboBox
private void Window_Loaded(object sender, RoutedEventArgs e)
{
comboBox1.Items.Insert(2, "Alice");
comboBox1.Items.Insert(5, "Bob");
comboBox1.Items.Insert(8, "Charlie");
}
情况 2 - 您有一个数据源,并且项目永远不会更改:
您可以使用数据源来填充ComboBox
. Any IEnumerable
type 可以用作数据源。你可以 -
- 绑定
ItemsSource
财产在XAML
到数据源,例如 -
<!-- MyDataSource is an IEnumerable type property in ViewModel -->
<ComboBox Height="23" Width="120" ItemsSource="{Binding MyDataSource}" />
- 将数据源分配给
ItemsSource
代码隐藏中的属性,例如 -
private void Window_Loaded(object sender, RoutedEventArgs e)
{
comboBox1.ItemsSource = new List<string> { "Alice", "Bob", "Charlie" };
}
情况 3 - 您有一个数据源,并且项目可能会更改
- You should use an
ObservableCollection<T>
作为数据源
- You should绑定
ItemsSource
财产在XAML
到数据源(如上所示)
- You can将数据源分配给
ItemsSource
代码隐藏中的属性(如上所示)
使用ObservableCollection<T>
确保每当向数据源添加或删除项目时,更改都会立即反映在 UI 上。这取决于你如何填充ObservableCollection<T>
.