在WPF中若需要绑定List<string>
对象到ItemsSource
属性,具体操作步骤:
1 生成水果类
Fruits.cs
namespace WpfApp1
{
public class Fruits
{
public Fruits()
{
Items = new List<string>
{
"苹果",
"梨",
"桔子",
"桃子"
};
}
public List<string> Items { get; set; }
}
}
2 修改XAML文件
MainWindow.xaml
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="150" Width="300">
<Window.Resources>
<local:Fruits x:Key="key_Fruits"/>
</Window.Resources>
<Grid>
<ComboBox HorizontalAlignment="Left" DataContext="{StaticResource key_Fruits}" ItemsSource="{Binding Items}" SelectedIndex="0" Margin="44,27,0,0" VerticalAlignment="Top" Width="120"/>
</Grid>
</Window>