如何使用MVVM在ListBox中显示字符串?

时间:2012-06-25 15:09:08

标签: c# wpf data-binding mvvm

我在WPF表单上有一个ListBox。我想水平显示字符串项列表。我有Grid持有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>

2 个答案:

答案 0 :(得分:3)

您需要在DisplayMemberPath

中设置ListBox

答案 1 :(得分:0)

这似乎已经成功了。

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