2011-10-05 65 views
0

我在下面有一些简单的XAML,我的问题是,为什么不在列表框中显示文本?我得到的是两条可选择的线路!仅在XAML中绑定XML属性

<Window x:Class="DataTemplateEditor.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="MainWindow" Height="350" Width="525"> 
<Grid> 
    <Grid.DataContext> 
     <XmlDataProvider Source="datatemplate.xml" XPath="Tables/Table" /> 
    </Grid.DataContext> 
    <DockPanel HorizontalAlignment="Stretch" Name="dockPanel1" VerticalAlignment="Stretch"> 
     <ListBox Name="listBox1" Width="150" DockPanel.Dock="Left" ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True"> 
      <ListBox.Resources> 
       <DataTemplate x:Key="MyDataTemplate"> 
        <StackPanel Orientation="Vertical"> 
         <TextBlock Text="{Binding [email protected]}" /> 
        </StackPanel> 
       </DataTemplate> 
      </ListBox.Resources> 
     </ListBox> 
     <ListView Name="listBox2" DockPanel.Dock="Right" /> 
    </DockPanel> 
</Grid> 

<?xml version="1.0" encoding="utf-8" ?> 
<Tables> 
    <Table Name="People"> 
    <Field Name="id" Type="Number" PrimaryKey="true" Indexed="true" AllowNull="false"/> 
    <Field Name="FirstName" Type="Number" PrimaryKey="true" Indexed="true" AllowNull="false"/> 
    </Table> 
    <Table Name="Purchases"> 
     <Field Name="id" Type="Number" PrimaryKey="true" Indexed="true" AllowNull="false"/> 
    </Table> 
</Tables> 

回答

0

您声明命名数据模板中Resources,但你永远不使用它。这就像初始化一个方法内的一个变量,但从来没有使用它的值:它什么都不做。

做你想要什么,模板分配到the ItemTemplate property

<ListBox ItemsSource="{Binding}"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <StackPanel Orientation="Vertical"> 
       <TextBlock Text="{Binding [email protected]}" /> 
      </StackPanel> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

但我认为StackPanel是不必要的存在。更重要的是,整个模板是不必要的,您可以使用DisplyMemberPath

<ListBox ItemsSource="{Binding}" DisplayMemberPath="@Name" />