1. 程式人生 > >WPF Combobox繫結List

WPF Combobox繫結List

在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>

3 執行程式

執行介面