Reputation: 423
I have a question. When Binding
items to a ListBox
it adds them vertically. For example where ItemsSource = "{Binding Path = Name}"
, and Name
is Bill
, I get the output in ListBox
for each char in on line (like this: B\ni\nl\nl). Where am I doing wrong?
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;
}
}
Upvotes: 0
Views: 542
Reputation: 17063
Your DataContext
is set to customers. The ItemsSource
should be set to the ObservableCollection
and DisplayMemberPath
is for showing the right property of your Customer.
<ListBox ItemsSource="{Binding customerOC}" DisplayMemberPath="Name" />
Upvotes: 1