2013-04-25 126 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控件構建了任何模板,並綁定到綁定對象的不同屬性。