将项目绑定到列表框会垂直添加它们

本文关键字:垂直 添加 项目 绑定 列表 | 更新日期: 2023-09-27 18:00:51

我有个问题。当Binding项目到ListBox时,它会垂直添加它们。例如,在ItemsSource = "{Binding Path = Name}"NameBill的情况下,我在ListBox中获得行中每个字符的输出(如下所示:B''ni''nl''nl(。我哪里做错了?

XAML:

<Window x:Class="ObservableColl.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ListBox HorizontalAlignment="Left" Height="244" Margin="313,28,0,0" VerticalAlignment="Top" Width="177" ItemsSource="{Binding Path=Name}"/>
    </Grid>
</Window>

C#:

    class Customer
    {
        public string Name{get; set;}
    }
    class Customers
    {
        public ObservableCollection<Customer> customerOC{get; set;}
        public Customers()
        {
            customerOC = new ObservableCollection<Customer>();
        }
        public void AddCustomer(Customer c)
        {
             customerOC.Add(c);
        }
    }
public partial class MainWindow:Window
{
    Customers customers{get; set;}
    public MainWindow()
    {
        InitializeComponent();
        customers = new Customers();
        customers.AddCustomer(new Customer(){Name = "Frank"});
        this.DataContext = customers;
    }
}

将项目绑定到列表框会垂直添加它们

您的DataContext已设置为客户。ItemsSource应设置为ObservableCollectionDisplayMemberPath用于显示客户的正确属性。

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