tags:

views:

97

answers:

3

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 ı want to make bindng operations in code behind -dont 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=)

A: 

Hi David,

Why don't you want to set the items source? What are you trying to achieve exactly?
Do you want everything in the code behind ? and why?

Clueless
Hi, in deed David didn't ask the question, it was me=)I don't want to use it since my technical advisor told me not to use item source, he told me to do this job in code behind. and in deed i don't know how exactly achieve this, now i know that i want to be able to run the code like binding b=new binding().... and want someone to help me on binding on xaml side too...
cemregoksu
A: 

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

Mark
+1  A: 

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.

Robert Rossney