typos
typos

Reputation: 6662

How to pass data from DataContext to ListBox in WPF?

I have a class defined like:

public class Agent 
{
    public int Id { get; set; }

    public string Category { get; set; }

    // rest removed for brevity 
}

Then, in WPF, I get the data as List and pass it to DataContext as this:

List<Agent> agents; // this includes my data
this.DataContext = agents;

And in .xaml part I want to list the Category field of each object. I have something like this:

<ListBox
    Name="agentCategoryListBox"
    Grid.Row="2"
    Grid.Column="1"
    ItemSource="{Binding Path=Category"} />

But this doesn't seem to work correctly. Any ideas?

Upvotes: 0

Views: 6883

Answers (6)

user7816380
user7816380

Reputation:

I also would suggest you to use MVVM. But if you do not want to then try this.

XAML:

<ListBox Name="AgentCategoryListBox" ItemsSource="{Binding}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <TextBlock Text="{Binding Category}" d:DataContext="{d:DesignData}" />
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

CS:

public MainWindow()
{
  InitializeComponent();

  List<Agent> agents = new List<Agent>
  {
    new Agent
    {
      Category = "Category"
    }
  };

  DataContext = agents;
}

public class Agent
{
  public string Category
  {
    get;
    set;
  }
}

Upvotes: 0

Tarboeuf
Tarboeuf

Reputation: 90

The fastest way to get what you want is :

<ListBox
    Name="agentCategoryListBox"
    Grid.Row="2"
    DisplayMemberPath="Category"
    Grid.Column="1"
    ItemSource="{Binding Path=."} />

ItemsSource is binded directly to your Datacontext (which is your list) And then you tell to your ListBox to display the property Category.

But the proper way would have been :

1 - Create a DataContext

public class AgentsDC
{
    public List<Agent> Agents { get; set; }
}

2 - Give this class as DataContext

this.DataContext = new AgentsDC();

3 - Bind all these things

<ListBox
    Name="agentCategoryListBox"
    Grid.Row="2"
    DisplayMemberPath="Category"
    Grid.Column="1"
    ItemSource="{Binding Path=Agents"} />

Upvotes: 0

Naresh Ravlani
Naresh Ravlani

Reputation: 1620

Let me help you to do this in the correct way as Alex suggested.

Create a list and populate it in ViewModel like this

ViewModel

public class MainWindowViewModel : INotifyPropertyChanged
    {

        public MainWindowViewModel()
        {
            agents = new ObservableCollection<Agent>();
            LoadData();
        } 


    private void LoadData()
        {            
            agents.Add(new Agent { Id = 1, Category = "a" });
            agents.Add(new Agent { Id = 2, Category = "b" });
            agents.Add(new Agent { Id = 3, Category = "c" });
        }
    }

In XAML, Make your list and use data template like this:

    <Window.Resources>
        <DataTemplate x:Key="AItemTemplate">
            <TextBlock Text="{Binding Category}"></TextBlock>
        </DataTemplate>
    </Window.Resources>

<ListBox ItemsSource="{Binding agents}" 
         ItemTemplate="{StaticResource AItemTemplate}"></ListBox>

That is it !!

Upvotes: 1

kritikaTalwar
kritikaTalwar

Reputation: 1740

may be this will give you an idea:

http://www.c-sharpcorner.com/forums/wpf-datacontext-binding-with-listbox

Upvotes: 0

Coskun Ozogul
Coskun Ozogul

Reputation: 2487

You try to bind your listbox to a string property.

You can try this : Give a name to your user control for exemle myUC Add a property to your user control :

 public List<Agent> AgentList { get; set; };

Fill your agentlist :

this.AgentList = //fill method

And bind your listbox like this :

<ListBox
Name="agentCategoryListBox"
Grid.Row="2"
Grid.Column="1"
ItemSource="{Binding Path=AgentList, ElementName=myUC"} />

Upvotes: 0

Alex Paven
Alex Paven

Reputation: 5549

Normally the DataContext would be a view model class that would contain the list of agents; then you can bind the ItemsSource to that list. Any of the many examples that deal with listbox will be pretty straight forward when it comes to that. Not really sure how the binding should look like if the list itself is the DataContext.

Then once the ItemsSource is set to a list of agents, if you want to show the Category in the list, the simpler way is to set DisplayMemberPath to "Category".

I suggest looking into MVVM and learning to apply it, it's an invaluable concept in my opinion.

Upvotes: 1

Related Questions