views:

722

answers:

1

The Scenario Bit:

On one of the controls within my Silverlight application I have embedded a custom user control. Within this embedded control is another custom user control that contains a datagrid. I would like to use binding to populate the datagrid. Easy enough I just sepcificy a collection that is in the DataContext of the parent control.

Parent Form:

<UserControl x:Class="ParentControl"
             ...>
    <Grid x:Name="LayoutRoot" >        
        <ReusableControl />
    </Grid>
</UserControl>

Parent Codebehind:

public partial class ParentControl: UserControl 
    {

        public ParentControl()
        {
            InitializeComponent();
            this.DataContext = ObjectCollection;
        }

        public ObservableCollection<object> ObjectCollection
        {
            get ;
            set ;
        }
    }

Intermediate Form

<UserControl x:Class="ReusableControl"
             ...>
    <Grid x:Name="LayoutRoot" Background="Gold">        
        <CustomDataGrid />
    </Grid>
</UserControl>

Child Control:

<UserControl x:Class="CustomDataGrid"
             ...>
    <Grid x:Name="LayoutRoot">        
        <data:DataGrid x:Name="dgItems"
                       AutoGenerateColumns="True"
                       ItemsSource="{Binding ObjectCollection}"
                       >
        </data:DataGrid>
    </Grid>
</UserControl>

The Question Bit:

I want to specificy the columns of the datagrid dynamically, based on another collection in the parent control DataContext. How can I do this? Is there more than one way of skinning this cat?*

Thanks, Mark

*No cats where harmed during the asking of this question.

A: 

After many hours I have found a work-around which I have posted here. This doesn't strike me as the best solution in the world, but it works, and doesn't need the registration of event handlers throughout the application. Also it works top down, which is what I wanted.

I suspect that I could use Dependency Properties a little better, to prevent the need for DP's and NP's in the same class, but I'm out of time :-(

Hope this helps someone else.

Mark Cooper