2012-06-25 23 views
0

我有一個WPF窗體上的ListBox。我想水平顯示字符串項目的列表。我有一個Grid持有我的ListBox控制。如何使用MVVM在ListBox中顯示字符串?

當我運行窗體時,它顯示封裝對象的名稱:ProjectName.Folder.Category而不是其中的字符串對象。

ViewModelLocator

public CategoryViewModel CategoryViewModel 
{ 
    get 
    { 
     if (categoryviewModel == null) 
     { 
      categoryviewModel = new CategoryViewModel(); 
      categoryviewModel.ListData.Clear(); 
      categoryviewModel.ListData.Add(new Category { MyCategory = "new categroy1" }); 
      categoryviewModel.ListData.Add(new Category { MyCategory = "new categroy2" }); 
      categoryviewModel.ListData.Add(new Category { MyCategory = "new categroy3" }); 
      categoryviewModel.ListData.Add(new Category { MyCategory = "new categroy4" }); 
      categoryviewModel.ListData.Add(new Category { MyCategory = "new categroy5" }); 
      categoryviewModel.ListData.Add(new Category { MyCategory = "new categroy6" }); 
     } 
     return categoryviewModel; 
    } 
} 

Model

class Category 
{ 
    public String MyCategory { get; set; } 
} 

MainPage.xaml

<Grid> 
    <my:featureControl HorizontalAlignment="Left" 
         x:Name="featureControl1" 
         VerticalAlignment="Top" Height="332" 
         Loaded="featureControl1_Loaded" /> 
</Grid> 

Control.xaml

<UserControl x:Class="AmebaPrototype.UI.Longlist.CategoryControl" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     mc:Ignorable="d" 
     d:DesignHeight="300" d:DesignWidth="1280"> 
<Grid DataContext="{Binding Source={StaticResource viewModelLocator},Path=CategoryViewModel}"> 

    <ListBox Height="300" HorizontalAlignment="Left" Name="listBox1" VerticalAlignment="Top" Width="1280" ItemsSource="{Binding ListData}" > 
     <ListBox.ItemsPanel> 
      <ItemsPanelTemplate> 
       <VirtualizingStackPanel Orientation="Horizontal"/> 
      </ItemsPanelTemplate> 
     </ListBox.ItemsPanel>   
    </ListBox> 
</Grid> 

回答

3

您需要設置DisplayMemberPathListBox

+3

...或指定一個ItemTemplate。 –

0

這似乎已經完成了帽子戲法。

<DataTemplate x:Key="ListBoxTemplate"> 
    <TextBlock x:Name="black" Text="{Binding MyCategory}"/> 
</DataTemplate> 
+1

它會工作,但只需在您的ListBox行上放置DisplayMemberPath =「MyCategory」就簡單得多:) –

+0

是的,只是做了那個,謝謝@DeanChalk。我會在幾分鐘內接受你的答案,當它讓我:) – Fabii

相關問題