WPF 用 collection 成员 属性 填充列表框

WPF fill Listbox with collection member property

我正在处理在我的 WPF 应用程序的某种列表中显示的食谱列表。 我有 collection 个食谱

public Cookbook()
{
   RecipeList=new ObservableCollection<Recipe>();
   AddRecipe(new Recipe("Food1", 0, null));
}

每个食谱都有 属性 名称。public string Name { get; set; }

我现在正在做的是用这个 collection

填充列表
<ListView x:Name="CategoriesListBox" Margin="10,0,10,0" ItemsSource="{Binding RecipeList}"
        Loaded="CategoriesListBox_OnLoaded" 
        SelectionChanged="CategoriesListBox_SelectionChanged">
        <ListBox.DataContext>
           <Implementation:Cookbook/>
        </ListBox.DataContext>
</ListView>

这当然会导致包含 object 个名称的列表 - 我想要列表中的食谱名称。有没有办法在列表框中显示 属性 名称?

(我正在寻找 XAML 解决方案 - 没有隐藏代码)

// 我已经尝试将 ListView 和嵌套的 Gridview 作为解决方案 - 这可行,但这也会在顶部创建不必要的网格和 header 字段。

<ListView x:Name="CategoriesListBox" Margin="10,0,10,0" ItemsSource="{Binding RecipeList}"
    Loaded="CategoriesListBox_OnLoaded" 
    SelectionChanged="CategoriesListBox_SelectionChanged">
    <ListBox.DataContext>
        <Implementation:Cookbook/>
    </ListBox.DataContext>

    <ListView.View>
        <GridView AllowsColumnReorder="False">
            <GridView.Columns>
                <GridViewColumn DisplayMemberBinding="{Binding Path=Name, Mode=OneWay}" />
            </GridView.Columns>
        </GridView>
    </ListView.View>
</ListView>

谢谢

使用ListView的DisplayMemberPath 属性。 将其设置为 Name

DisplayMemberPath="Name"

https://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.displaymemberpath(v=vs.110).aspx

使用 ListBox 而不是 ListView,并设置其 DisplayMemberPath 属性:

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

或设置其ItemTemplate属性:

<ListBox ItemsSource="{Binding RecipeList}" ...>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>