Edit this page

ElementName binding in column Header or CellTemplate

PROBLEM

The ElementName binding does not work when used in column Header or CellTemplate. For example this will not work:

XAML

<TextBox x:Name="TextBox1" Text="Type something" />

<telerik:RadGridView ItemsSource="{Binding}" AutoGenerateColumns="False">
    <telerik:RadGridView.Columns>
        <telerik:GridViewColumn>
            <telerik:GridViewColumn.Header>
                <TextBlock Text="{Binding Text, ElementName=TextBox1}" />
            </telerik:GridViewColumn.Header>
            <telerik:GridViewColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Text, ElementName=TextBox1}" />
                </DataTemplate>
            </telerik:GridViewColumn.CellTemplate>
        </telerik:GridViewColumn>
    </telerik:RadGridView.Columns>
</telerik:RadGridView>

CAUSE

When you use the ElementName, the binding engine uses FindName method on FrameworkElement to find the target just once.
So when you load it with LoadContent (as we do in RadGridView) – the element is not yet in the visual tree and FindName fails.

SOLUTION

Use a Style to set the ContentTemplate as below:

XAML

<TextBox x:Name="TextBox2" Text="Type something" />

<telerik:RadGridView ItemsSource="{Binding}" AutoGenerateColumns="False">
    <telerik:RadGridView.Columns>
        <telerik:GridViewColumn>
            <telerik:GridViewColumn.HeaderCellStyle>
                <Style TargetType="telerik:GridViewHeaderCell">
                    <Setter Property="ContentTemplate">
                        <Setter.Value>
                            <DataTemplate>
                                <TextBlock Text="{Binding Text, ElementName=TextBox2}" />
                            </DataTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </telerik:GridViewColumn.HeaderCellStyle>
            <telerik:GridViewColumn.CellStyle>
                <Style TargetType="telerik:GridViewCell">
                    <Setter Property="ContentTemplate">
                        <Setter.Value>
                            <DataTemplate>
                                <TextBlock Text="{Binding Text, ElementName=TextBox2}" />
                            </DataTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </telerik:GridViewColumn.CellStyle>
        </telerik:GridViewColumn>
    </telerik:RadGridView.Columns>
</telerik:RadGridView>

See Also