3
votes

I have a GridView control and I am adding GridViewColumns. I was using DisplayMemberBinding property of GridViewColumn but now I want to use the CellTemplate. I am binding to a dictionary.

The following code worked with DisplayMemberBinding:

var column = new GridViewColumn
{
    Header = current.Key,
    DisplayMemberBinding = new Binding("[" + current.Key + ]")
};

Now, I need to do the same with CellTemplate but for some reason I am not sure why it is not displaying the items.

var column = new GridViewColumn
{
    Header = current.Key,
    CellTemplate = (DataTemplate)FindResource("GridViewTextBlockDataTemplate"),
};

And here is the DataTemplate defined in Window.Resources:

<DataTemplate x:Key="GridViewTextBlockDataTemplate" x:Name="GridViewTextBlockDataTemplate">
    <TextBlock Text="{Binding Path=[Key]}"></TextBlock>
</DataTemplate>

Thanks, Azam

1
Is the FindResource method returning null or an actual DataTemplate? If it is returning null, try this.Resources["GridViewTextBlockDataTemplate"].Charlie
It returns the DataTemplate. I removed the DisplayMemberBinding and added the CellTemplate. But now how do I change the TextBlock Text at runtime.azamsharp
I have a similar requirement. Any luck ?Angshuman Agarwal

1 Answers

0
votes

Your solution is correct except that to get the value in the textblock you just need to have Keyword Binding and no need to provide path as you are binding the datatemplate, it automatically assigns the value.

If that does not work try to use datatemplate selector for the datagrid and For a detailed explanation on datatemplate selector please have a look a these link: WPF DataTemplate Selector Tutorial