I want to display CustomerList\CustomerName property items to the ListBox using ItemsSource DisplayMemberPath property only. But it is not working. I do not want to use DataContext or any other binding in my problem. Please help.
My code is given below:
MainWindow.xaml.cs
namespace BindingAnItemControlToAList
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
public class Customer
{
public string Name {get;set;}
public string LastName { get; set; }
}
public class CustomerList
{
public List<Customer> Customers { get; set; }
public List<string> CustomerName { get; set; }
public List<string> CustomerLastName { get; set; }
public CustomerList()
{
Customers = new List<Customer>();
CustomerName = new List<string>();
CustomerLastName = new List<string>();
CustomerName.Add("Name1");
CustomerLastName.Add("LastName1");
CustomerName.Add("Name2");
CustomerLastName.Add("LastName2");
Customers.Add(new Customer() { Name = CustomerName[0], LastName = CustomerLastName[0] });
Customers.Add(new Customer() { Name = CustomerName[1], LastName = CustomerLastName[1] });
}
}
}
**MainWindow.Xaml**
<Window x:Class="BindingAnItemControlToAList.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:BindingAnItemControlToAList"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded" >
<Window.Resources>
<local:CustomerList x:Key="Cust"/>
</Window.Resources>
<Grid Name="Grid1">
<ListBox ItemsSource="{Binding Source={StaticResource Cust}}" DisplayMemberPath="CustomerName" Height="172" HorizontalAlignment="Left" Margin="27,23,0,0" Name="lstStates" VerticalAlignment="Top" Width="245" />
</Grid>
</Window>
Your’re not setting a “collection” as the ItemsSource…thus you don’t get anything to choose from. This will choose the list
CustomerName.But really, you should restructure your
CustomerListclass…there’s no need to have separate lists that copy theNameandLastNamefields of theCustomer– it means you are duplicating data unnecessarily, and also it’s possible for the data to get out of sync with each collection.You also should consider using INotifyPropertyChanged, and use INotifyCollectionChanged on your classes (e.g. use
ObservableCollectioninstead ofList, and implementINotifyPropertyChangedon theCustomerclass) if it’s possible to change the collection or data.e.g.