WPF Templates and DataContext Binding in GridView

I am trying to create a series of related columns in a RadGridView, and I am using a template to create hyperlinks in two columns. Here is basically what I have:

<telerik:GridViewDataColumn IsReadOnly="True" UniqueName="Distributor" DataContext="{Binding Distributor}" CellTemplate="{StaticResource linkTemplate}"/> 

and

  <DataTemplate x:Key="linkTemplate"> <TextBlock> <Hyperlink DataContext={TemplateBinding DataContext} Click="Hyperlink_Click"> <TextBlock Text="{Binding Name}" /> </Hyperlink> </TextBlock> </DataTemplate> 

RadGridView itself is associated with a set of DistributorContainer objects, which, among other things, have the Distributor property. The linkTemplate link refers directly to the properties of the Distributor object, so the datacontext hyperlink must be installed on the Distributor.

Unfortunately, the hyperlink data context is a DistributorContainer object. I use linkTemplate (as well as the Hyperlink_Click handler) in lists that bind to Distributor lists, and I would really like to reuse this template because it is basically the same.

Why does the template not get the Distributor as its DataContext through the TemplateBinding for the GridViewDataColumn?

+6
c # data-binding telerik wpf datatemplate
source share
1 answer

Here is an example of how to achieve this:

Xaml

 <Grid> <Grid.Resources> <DataTemplate x:Key="linkTemplate"> <TextBlock> <Hyperlink> <TextBlock Text="{Binding Value.Name, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type telerik:GridViewCell}}}" /> </Hyperlink> </TextBlock> </DataTemplate> </Grid.Resources> <telerik:RadGridView ItemsSource="{Binding}" AutoGenerateColumns="False"> <telerik:RadGridView.Columns> <telerik:GridViewDataColumn DataMemberBinding="{Binding Distributor1}" CellTemplate="{StaticResource linkTemplate}" /> <telerik:GridViewDataColumn DataMemberBinding="{Binding Distributor2}" CellTemplate="{StaticResource linkTemplate}" /> </telerik:RadGridView.Columns> </telerik:RadGridView> </Grid> 

FROM#

 namespace WpfApplication1 { public partial class Window1 : Window { public Window1() { InitializeComponent(); DataContext = from i in Enumerable.Range(0, 10) select new DistributorContainer() { ID = i, Distributor1 = new Distributor() { Name = String.Format("Distributor1 Name{0}", i) }, Distributor2 = new Distributor() { Name = String.Format("Distributor2 Name{0}", i) } }; } } public class DistributorContainer { public int ID { get; set; } public Distributor Distributor1 { get; set; } public Distributor Distributor2 { get; set; } } public class Distributor { public string Name { get; set; } } } 
+10
source share

All Articles