2011年8月11日 星期四

Expression Blend(39)-繫結到Observable Collection

本範例使用WPF專案
若有一個 Observable Collection定義如下,要將其繫結到ListBox
class BookList : ObservableCollection<Book> {
        public BookList ( )
            : base ( ) {
            Add ( new Book { Title = "Learning ASP.NET" , Price = 590 } );
            Add ( new Book { Title = "Learning VB" , Price = 490 } );
            Add ( new Book { Title = "Learning C#" , Price = 600 } );
            Add ( new Book { Title = "Learning Blend" , Price = 500 } );
        }
    }
    class Book {
        public string Title { get; set; }
        public int Price { get; set; }
    }
  • 加一個ListBox
  • Create Object Data Source
image
  • 選BookList
image
  • Bind
image
  • 效果如下
image
  • 編輯Data Template
image
  • 修改StackPanel Orientation
image
  • 使用拖曳方式,調整TextBlock順序
image
  • 加個TextBlock到Template
image
參考XAML如下
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication7" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"
    x:Class="WpfApplication7.Window1"
    x:Name="Window"
    Title="Window1"
    Width="640" Height="480">
    <Window.Resources>
        <local:BookList x:Key="BookListDataSource" d:IsDataSource="True"/>
        <DataTemplate x:Key="BookTemplate">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Title}"/>
                <TextBlock x:Name="textBlock" TextWrapping="Wrap" Text=" - "/>
                <TextBlock><Run Text="590"/></TextBlock>
            </StackPanel>
        </DataTemplate>
    </Window.Resources>
    <Grid x:Name="LayoutRoot" DataContext="{Binding Source={StaticResource BookListDataSource}}">
        <ListBox x:Name="listBox" Height="144" Margin="168,40,0,0" VerticalAlignment="Top" ItemTemplate="{DynamicResource BookTemplate}" ItemsSource="{Binding}" HorizontalAlignment="Left" Width="144"/>
    </Grid>
</Window>

沒有留言:

總瀏覽量