WEB开发网
开发学院WEB开发ASP.NET WPF学习笔记10. Binding (3) 阅读

WPF学习笔记10. Binding (3)

 2010-10-11 16:29:53 来源:本站整理   
核心提示:6. 数据模板数据模板为展示数据提供了极大的灵活性,我们继续以前面的例子来看看它的能力,WPF学习笔记10. Binding (3),<Windowx:Class="Learn.WPF.Window1"xmlns="http://schemas.microsoft.com/winfx

6. 数据模板数据模板为展示数据提供了极大的灵活性,我们继续以前面的例子来看看它的能力。

<Window x:Class="Learn.WPF.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:my="clr-namespace:Learn.WPF"
  Title="Window1">
  <Window.Resources>
    <my:PersonalList x:Key="personals" >
      <my:Personal Name="Tom" Age="10" Sex="Male" />
      <my:Personal Name="Mary" Age="15" Sex="Female" />
      <my:Personal Name="Jack" Age="12" Sex="Male" />
    </my:PersonalList>
  </Window.Resources>
  <Grid>
    <StackPanel DataContext="{StaticResource personals}">
      <ListBox x:Name="listbox1" ItemsSource="{Binding}">
        <ListBox.ItemTemplate>
          <DataTemplate>
            <StackPanel Orientation="Horizontal">
              <TextBlock Text="{Binding Path=Name}" />
              <TextBlock>, </TextBlock>
              <TextBlock Text="{Binding Path=Age}" />
              <TextBlock>,</TextBlock>
              <TextBlock Text="{Binding Path=Sex}" />
            </StackPanel>
          </DataTemplate>
        </ListBox.ItemTemplate>
      </ListBox>
    </StackPanel>
  </Grid>
</Window>

很显然,利用 ListBox.ItemTemplate.DataTemplate 我们可以用更复杂和更丰富的手段显示数据源对象,不再仅仅是通过 Path 显示某单个属性。不过通常情况下,我们会像 HTML/CSS 那样将数据模板定义到资源中,以便在多个地方重复使用。

<Window x:Class="Learn.WPF.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:my="clr-namespace:Learn.WPF"
  Title="Window1">
  <Window.Resources>
    <my:PersonalList x:Key="personals" >
      <my:Personal Name="Tom" Age="10" Sex="Male" />
      <my:Personal Name="Mary" Age="15" Sex="Female" />
      <my:Personal Name="Jack" Age="12" Sex="Male" />
    </my:PersonalList>

    <DataTemplate x:Key="myData">
      <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Path=Name}" />
        <TextBlock>,</TextBlock>
        <TextBlock Text="{Binding Path=Age}" />
        <TextBlock>,</TextBlock>
        <TextBlock Text="{Binding Path=Sex}" />
      </StackPanel>
    </DataTemplate>
  </Window.Resources>
  <Grid>
    <StackPanel DataContext="{StaticResource personals}">
      <ListBox x:Name="listbox1" ItemsSource="{Binding}" 
        ItemTemplate="{StaticResource myData}">
      </ListBox>
    </StackPanel>
  </Grid>
</Window>

1 2 3 4 5  下一页

Tags:WPF 学习 笔记

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接