2013-04-25 123 views
0

所以我最终决定从WinForms转移到WPF,并且我的旅程非常有趣。我有一个简单的应用程序,我将ObservableCollection绑定到ListBox绑定到WPF中的集合

我有一个Animal实体:

namespace MyTestApp 
{ 
    public class Animal 
    { 
     public string animalName; 
     public string species; 

     public Animal() 
     { 
     } 

     public string AnimalName { get { return animalName; } set { animalName = value; } } 
     public string Species { get { return species; } set { species = value; } } 
    } 
} 

而一个AnimalList实体:

namespace MyTestApp 
{ 
    public class AnimalList : ObservableCollection<Animal> 
    { 
     public AnimalList() : base() 
     { 
     } 
    } 
} 

最后,这里是我的主窗口:

<Window x:Class="MyTestApp.Window3" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="clr-namespace:MyTestApp" 
    Title="Window3" Height="478" Width="563"> 

<Window.Resources> 
    <local:AnimalList x:Key="animalList"> 
     <local:Animal AnimalName="Dog" Species="Dog"/> 
     <local:Animal AnimalName="Wolf" Species="Dog"/> 
     <local:Animal AnimalName="Cat" Species="Cat"/> 
    </local:AnimalList>  
</Window.Resources> 

<Grid> 
    <StackPanel Orientation="Vertical" Margin="10,0,0,0"> 
     <TextBlock FontWeight="ExtraBold">List of Animals</TextBlock> 
     <ListBox ItemsSource="{Binding Source={StaticResource animalList}, Path=AnimalName}"></ListBox> 
    </StackPanel> 
</Grid> 

现在,当我运行应用程序,我看到填充了三个项目的列表框:“d”,“O”,而不是“狗”,“G”,“狼”和“猫”:

enter image description here

我有一种强烈的感觉,我在某个地方做了一些愚蠢的事情(AnimalList构造函数可能?),但我无法弄清楚它是什么。任何帮助表示赞赏。

回答

1

您需要设置DisplayMemberPath(而不是绑定中的Path属性)。

<Grid> 
    <StackPanel Orientation="Vertical" Margin="10,0,0,0"> 
     <TextBlock FontWeight="ExtraBold">List of Animals</TextBlock> 
     <ListBox ItemsSource="{Binding Source={StaticResource animalList}}" DisplayMemberPath="AnimalName"></ListBox> 
    </StackPanel> 
</Grid> 

既然你绑定到动物对象的列表,DisplayMemberPath指定要显示的列表项动物类属性的名称。

如果属性本身是一个对象,你可以使用点表示法指定的完整路径,你想显示即财产..

<ListBox ItemsSource="{Binding Source={StaticResource animalList}}" DisplayMemberPath="PropertyInAnimalClass.PropertyInTheChildObject.PropertyToDisplay" /> 
+0

宾果。那就是诀窍。 – PoweredByOrange 2013-04-25 22:54:04

0

你的列表框绑定到animalname。相反,你应该你的列表框绑定到您的收藏:

<ListBox ItemsSource="{Binding Source={StaticResource animalList}}"></ListBox> 

请注意,我已经删除从绑定的path=AnimalName

现在您将看到类名,因为ListBox不知道如何显示Animal,因此它会调用它的ToString-方法。

您可以通过给它像这样一个ItemTemplate解决这个问题:

<ListBox ItemsSource="{Binding Source={StaticResource animalList}}"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <StackPanel>  
       <TextBlock Text="{Binding AnimalName}" /> 
      </StackPanel> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

ItemTemplate中你的DataContext是Animal一个实例里面,然后你可以绑定到该实例的属性。在我的示例中,我已经绑定了AnimalName,但是您基本上使用常规XAML控件构建了任何模板,并绑定到绑定对象的不同属性。