cemregoksu
cemregoksu

Reputation: 841

Data Binding in Code Behind C#

I have a quite simple question:

I have a People property whose type is List< Person > and a Person has a Name and Surname. I want to show the Name on my listBoxPerson and I want to make binding operations in code behind - don't want to use ItemsSource property- Here is my code snippet:

Binding userBinding = new Binding();
        userBinding.Source =People;
        userBinding.Path = new PropertyPath("Person.Name");
        listBoxPerson.SetBinding(ContentProperty, userBinding);

and here is my xaml code:

 < ListBox Height="303" HorizontalAlignment="Left" Margin="12,108,0,0" Name="listBoxPerson" VerticalAlignment="Top" Width="234" >

        < ListBox.Resources >
            < ObjectDataProvider x:Key="UserData" ObjectType="local:Person"/ >
        < /ListBox.Resources >
        < ListBox.ItemTemplate >
            < DataTemplate >
                < Label Content="{Binding Path=Name}" ></Label  >
            < /DataTemplate >
        < /ListBox.ItemTemplate >
    < /ListBox >

this works when I write

listboxPerson.ItemsSource= People;

but there is nobody listed with the first given code. I am confused on how to solve this binding problem, and will be pleased with any help=)

Upvotes: 2

Views: 6767

Answers (2)

Robert Rossney
Robert Rossney

Reputation: 96722

This question doesn't really make any sense.

Is the idea that you're supposed to populate ListBox.Items in code instead of binding ItemsSource to a collection? If so, there's no need to create a binding at all; your code-behind should look something like:

MyListBox.Items.AddRange(myCollection);

Is the idea that you're supposed to create the binding to the Name property in code instead of in XAML? In that case, you need to find the Label object in the DataTemplate and create the binding on it. It's hard to imagine circumstances under which that would be a good idea.

If you're asked, "Why do it this way?", saying, "Because I was told to" really isn't an answer. You need to find out why you're being asked to do it this way. Among other things, knowing the reason will help you understand the question you're trying to ask.

Upvotes: 2

Mark
Mark

Reputation: 14930

have you tried the ItemsSourceProperty instead of the ContentProperty can you use that?

Upvotes: 0

Related Questions