views:

36

answers:

4

Is there a control in silverlight to group controls together for data binding. For instance, say I have a Person object and I want to display fname, lname, age, height, etc. in TextBlocks. Is there a control I can use to group these TextBlock controls together and set the ItemSource on just that control similar to how you set the ItemSource on a DataGrid and then bind each column?

A: 

You may want to read this article on MVVM http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

It sounds like you need to create a "PersonView" and a "PersonViewModel" (and probably a "PersonCollectionViewModel") This would allow you to bind the controls on your "PersonView" (A Silverlight UserControl) to the "PersonViewModel".

Ben
+1  A: 

Group the TextBlocks in any layout control and bind the control's DataContext to Person. If not explicitly set, each TextBlock's context will be relative to the parent.

<UserControl DataContext="">
    <UserControl.DataContext>
        <SomeViewModel />
    </UserControl.DataContext>
    <Grid DataContext="{Binding ThePerson}">
        <TextBlock Text="{Binding fname}"/>
        <TextBlock Text="{Binding lname}"/>
        <TextBlock Text="{Binding age}"/>
        <TextBlock Text="{Binding height}"/>
    </Grid>
</UserControl>

View model class...

public class SomeViewModel
{
    public Person ThePerson { get;set; }
}
Brandon Copeland
Then how do you bind the Grid to a specific instance of Person?
PhilBrown
Are you binding to Person in your view now? How? Maybe you can clarify a little better what you're trying to accomplish. Are you looking for a reusable control or just a way to logically organize the binding? Do you have just one Person or a collection?The assumption in my answer is you have a public property Person on the UserControl's DataContext. With MVVM, that data context would be a view model. I updated the code to better demonstrate.
Brandon Copeland
I might have misunderstood what you're looking for. This answer would provide a way to group binding for related textblocks (a ContentControl with a DataTemplate would work the same way).If your looking for a separate UserControl to encapsulate this, look into Ben's answer.If you have a collection of Persons, look into an ItemsControl like ListBox and set the DataTemplate. Items in the DataTemplate will be similarly relative.
Brandon Copeland
A: 

You can use DataForm control and set its "IsReadOnly" property to True ,this control usually used to edit data, and remember to set AutoGenerateFields="True" ...

PS : I'm supposing you're using Ria service with silverlight

Al0NE
A: 

I think any of these answers is correct, however I don't think will work/are appropriate for my app. The MVVM approach is overkill for my app and the other two approaches will not work for me for various reasons. I will just do everything in the code-behind.

PhilBrown