views:

309

answers:

1

In a window of my WPF application I have several hundreds of objects, they based on a custom control. They differ from each other only by name:

...
<MyNamespace:MyCustControl x:Name="x4y3" />
<MyNamespace:MyCustControl x:Name="x4y4" />
<MyNamespace:MyCustControl x:Name="x4y5" />
<MyNamespace:MyCustControl x:Name="x4y6" />
<MyNamespace:MyCustControl x:Name="x4y7" />
...

The custom control and, consequently, these objects have some number of properties. The values of these properties should be updated from a List(T) (or another type of generic collection) which is populated from a SQL Server database using LINQ to SQL query.

In order to distinguish which record corresponds to each object, we have a field in a collection with names of these objects: "x4y3", "x4y4", "x4y5", ... and so on.

My question is:

Is it possible to establish databinding connection of the total number of these objects to this generic collection, based on a condition of equality of the name of each object and the value of the corresponding field in generic collection?

+1  A: 

This is entirely possible using an ItemControl in conjunction with a DataTemplate. Instead of creating an explicit list of your custom control, create an ItemsControl and bind its ItemsSource property to your collection. Set the ItemTemplate to a DataTemplate containing your custom control.

Example:

<Window.Resources>
    <DataTemplate x:Key="MyTemplate">
        <MyNamespace:MyCustControl/>
    </DataTemplate>
</Window.Resources>
...
    <ItemsControl ItemsSource="{Binding MyCollection}" 
                  ItemTemplate="{StaticResource MyTemplate}"/>

To display values from your data object simply bind the elements in your custom control as they will each have a different data object as their DataContext.

Aviad P.
Thank you for giving direction! To be honest, I didn't even know how to approach this issue. But your words sound promising and now I am encouraged to learn and try this. But, frankly speaking, I don't understand how each object recognize to which record from a collection he corresponds. Where we use its name for getting know which record to read (or, to be correct, to databind)
rem
Names are not used here. When WPF generates the items for the list, it will set each item's `DataContext` property to the data object it represents. Then you can bind against that data objecy from within your `DataTemplate` or any child of it (your custom control for example).
Aviad P.
And one more thing, traditionally (before WPF came along) we were used to push our values from code to the display, WPF works best if you do this in reverse, put references to data in XAML and don't try to push data to the view from code.
Aviad P.