【问题标题】:WPF fill Listbox with collection member propertyWPF 用集合成员属性填充列表框
【发布时间】:2015-04-12 03:32:21
【问题描述】:

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

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

每个配方都有一个名为 Name.public string Name { get; set; }

的属性

我现在正在做的是用这个集合填充列表

<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>

这当然会导致列表中填充了对象名称 - 我想要列表中的配方名称。有没有办法在列表框中显示属性名称?

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

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

<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>

谢谢

【问题讨论】:

    标签: c# wpf xaml listbox


    【解决方案1】:

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

    DisplayMemberPath="Name"

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

    【讨论】:

      【解决方案2】:

      使用 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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-28
        • 1970-01-01
        • 1970-01-01
        • 2012-09-29
        • 1970-01-01
        • 2016-11-01
        相关资源
        最近更新 更多