【问题标题】:Binding items to listbox adds them vertically将项目绑定到列表框会垂直添加它们
【发布时间】:2013-02-22 17:48:39
【问题描述】:

我有一个问题。当 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;
    }
}

【问题讨论】:

  • 在类Customers的构造函数中,'customer'是什么?我没有看到这个变量的定义。
  • 对不起,它本来是customerOC。已编辑*
  • 你能展示你的完整 XAML

标签: c# wpf binding listbox


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    • 1970-01-01
    • 2014-06-09
    • 1970-01-01
    • 2013-07-07
    • 1970-01-01
    相关资源
    最近更新 更多