【问题标题】:How to bind object data from Combobox to ListBox如何将对象数据从组合框绑定到列表框
【发布时间】:2017-03-14 10:58:37
【问题描述】:

这是自定义对象:

public class FileItem
{
    public string Name { get; set; }
    public string Path { get; set; }
}

Collection:

public ObservableCollection<FileItem> collection { get; set; }

Combobox:

<ComboBox
    Name="cbCollection" 
    ItemsSource="{Binding interfaces}"/>

ListBox:

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

所以我的Combobox 填充了我的object 集合,我想在我的ListBox 中查看它的所有属性。

目前:

  1. 我只能看到属性Name
  2. 我可以看到我的Combobox 中的所有对象,而不仅仅是选定的对象。

【问题讨论】:

    标签: wpf data-binding listbox


    【解决方案1】:

    如果您想查看的不仅仅是名称属性,则需要扩展数据模板以包含其他属性。

    如果您想查看所选项目的属性,那么您应该绑定到组合框的SelectedItem 属性。实际上我不认为你想要ListBox,因为只有一个选定的项目。

    这应该让你开始:

    <ContentControl Content="{Binding ElementName=cbCollection, Path=SelectedItem}">
      <ContentControl.Resources>
        <DataTemplate DataType="{x:Type local:FileItem}">
          <TextBlock Text="{Binding Name}"/>
        </DataTemplate>
      </ContentControl.Resources>
    </ContentControl>
    

    【讨论】:

    • 我需要把这个 ContentControl 放在哪里?
    • 用它替换你的 ListBox。
    • 错误 5 值不能为空。参数名称:dataType 和错误 6 添加到 IDictionary 的所有对象都必须具有 Key 属性或与之关联的其他某种类型的键。
    • 仍然错误:在我的命名空间中找不到我的对象成员(名称)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-15
    • 1970-01-01
    • 2010-10-10
    • 2013-10-04
    • 2013-12-18
    • 2018-06-20
    • 1970-01-01
    相关资源
    最近更新 更多