[WPF] ListBox Data Binding

[WPF] ListBox Data Binding

在這裡用2種方法來實作(第2種方法其實只是第1種的變種而已,原理是一樣的)

同時包含Style & Template 的組合用法

首先新增一個Fruit class

class Fruit
    {
        public string Name { get; set; }
        public double Price { get; set; }
        public Fruit(string name, double price)
        {
            Name = name;
            Price = price;
        }
    }

 

再來新增一個Fruits class、一個FruitsSQL class、以及FruitsSQL的資料來源 DataAccess class

class Fruits: List<Fruit>
    {
        public Fruits() 
        {
            Add(new Fruit("Apple", 10));
            Add(new Fruit("Orange",5));
            Add(new Fruit("Lemon",4));
            Add(new Fruit("Mango",15));
            Add(new Fruit("Grape",13));
        }
    }
class FruitsSQL:List<Fruit>
    {
        public FruitsSQL()
        {
            AddRange(new DataAccess().getFruit());
        }
    }

 

class DataAccess
    {
        public DataAccess(){  }
 
        public List<Fruit> getFruit()
        {
            List<Fruit> FruitList = new List<Fruit>();
            string sConn = @"ConnectionString";
            using (SqlConnection conn = new SqlConnection(sConn))
            {
                SqlCommand cmd = new SqlCommand("select * from fruit", conn);//fruit table: name, price
                conn.Open();
 
                try
                {
                    SqlDataReader reader = cmd.ExecuteReader();
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            FruitList.Add(new Fruit(reader["name"].ToString(), int.Parse(reader["price"].ToString())));
                        }
                    }
                }
                catch (Exception ex)
                {
                    //error occur
                }
                finally
                {
                    conn.Close();
                }
            }
            return FruitList;
        }
    }

這樣子 ListBox Data 的來源就準備好了,接著看XAML的部分

 

<Window x:Class="WpfApplication4.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:src="clr-namespace:WpfApplication4.Data"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <Grid.Resources>
            <src:Fruits x:Key="myFruits"></src:Fruits>
            <src:FruitsSQL x:Key="myFruitsSQL"></src:FruitsSQL>
            <Style TargetType="{x:Type ListBoxItem}">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type ListBoxItem}">
                            <Border Name="border" BorderBrush="Black" BorderThickness="0,0,0,1" Background="LightGray">
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="{Binding Path=Name}" Width="100"></TextBlock>
                                <TextBlock Text="{Binding Path=Price}"></TextBlock>
                            </StackPanel></Border>
                            <ControlTemplate.Triggers>
                                <Trigger Property="IsSelected" Value="True">
                                    <Setter TargetName="border" Property="Background" Value="LightBlue"></Setter>
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </Grid.Resources>
        <ListBox Name="Fruitlist" ItemsSource="{StaticResource myFruits}" Margin="0,0,0,122">   
        </ListBox>
        <ListBox Name="Fruitlist2" ItemsSource="{StaticResource myFruitsSQL}" Height="114" VerticalAlignment="Bottom">
        </ListBox>
    </Grid>
</Window>

 

 

 

 

程式實際執行畫面:

image