views:

120

answers:

1

I need to dynamically add/remove GridView columns, each displaying information from a different element stored in a KeyedCollection (indexed with tn 'int'). The basic technique works, but requires an index, as follows:

<GridViewColumn Header="bid">
    <GridViewColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Width="60" DataContext="{Binding Elements}" Text="{Binding [546].PropName}" TextAlignment="Center" />
        </DataTemplate>
    </GridViewColumn.CellTemplate>
</GridViewColumn>

However, at run-time I need to add more of these, with different integer keys, at which point I'm not sure how to create new DataTemplates, each with a different binding index.

Constructing a new DataTemplate using the XamlParser seems quite ugly...

Any help?

A: 

Well, from what I seem to understand you need your objects to have some additional properties. Something like Key and ValueFromKey. This properties could look similar to this:

public int Key { get; set; }

public object ValueFromKey
{
   get { return this[Key]; }
}

Then at the moment you're adding the GridView columns you should set the Key property's value to the 'magic' number (like 546 from the example).

And your DataTemplate will look as simple as this:

<DataTemplate>
    <TextBlock 
        Width="60" 
        Text="{Binding ValueFromKey.PropName}" 
        TextAlignment="Center" 
        />
</DataTemplate>

The problem arises if you cannot change that class. Then you could probably consider wrapping it with your own class (kind of a ViewModel) and bind your UI to a collection of those new instances.

arconaut
Well, no quite. The problem is the so called 'magic' number is associated with the column (each column should use a different number) and the Key property you suggest will be associated with a row...