Artem Kyba
Artem Kyba

Reputation: 885

WPF: Bind text into Header DataGridColumn when it is hidden

Sample:

<Window.Resources>
    <BooleanToVisibilityConverter x:Key="BoolToVis" />
</Window.Resources>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition></RowDefinition>
        <RowDefinition></RowDefinition>
        <RowDefinition></RowDefinition>
        <RowDefinition></RowDefinition>
    </Grid.RowDefinitions>
    <Label Grid.Row="0" x:Name="label1" Content="Text"/>
    <ComboBox Grid.Row="1" SelectedIndex="0">
        <ComboBoxItem x:Name="it1">Item1</ComboBoxItem>
        <ComboBoxItem x:Name="it2">Item2</ComboBoxItem>
    </ComboBox>
    <DataGrid Background="Blue" Grid.Row="2" Visibility="{Binding ElementName=it1, Path=IsSelected, Converter={StaticResource BoolToVis}}">
        <DataGrid.Columns>
            <DataGridTextColumn>
                <DataGridTextColumn.Header >
                    <TextBlock Text="{Binding ElementName=label1, Path=Content}"/>
                </DataGridTextColumn.Header>
            </DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>
    <DataGrid Background="Red" Grid.Row="2" Visibility="{Binding ElementName=it2, Path=IsSelected, Converter={StaticResource BoolToVis}}">
        <DataGrid.Columns>
            <DataGridTextColumn>
                <DataGridTextColumn.Header >
                    <TextBlock Text="{Binding ElementName=label1, Path=Content}"/>
                </DataGridTextColumn.Header>
            </DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>
</Grid>

How to bind text from label1 into header in second DataGrid which was hidden before. This sample is not working.

Results: enter image description here

enter image description here

As you can see, from some reason, second DataGrid don't want to bind the text from Label

Upvotes: 2

Views: 443

Answers (1)

Rohit Vats
Rohit Vats

Reputation: 81333

Use x:Reference in place of ElementName and it will work:

<TextBlock Text="{Binding Source={x:Reference label1}, Path=Content}"/>

Issue is ElementName internally uses Visual tree to find source element object but since grid was collapsed initially it couldn't find it.

Whereas x:Reference doesn't use Visual tree internally. Hence, was able to resolve the binding even in collapsed state.

You can read more about it here - ElementName v/s x:Reference.

Upvotes: 2

Related Questions