Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi I have a DataGrid. I used TextBox in its cells.
I made a ControlTemplate for it.
So My problem is when I use controlTemplate, the Binding of TextBox won't work. But if I directly set everything in the DataTemplate, the Binding works perfect.
Any Idea please?

What I have tried:

Binding to TextBox works perfect in this code:
XML
<DataGridTemplateColumn Header="Text" IsReadOnly="False" Width="38*">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBox 
                Text="{Binding Path=TheText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                Background="Transparent"
                Foreground="White"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>


Binding to TextBox doesn't work in this code!!! :

XML
<DataGridTemplateColumn Header="Text" IsReadOnly="False" Width="38*">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBox 
                Text="{Binding Path=TheText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
                Template="{DynamicResource TextBoxOfCellsInDataGridOfSubtitle}"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
Posted
Updated 15-Jan-24 3:09am
v3

1 solution

I found the answer.
I should bind the Text to parent, then bind to the Class.

XML
<DataGridTemplateColumn Header="Text" IsReadOnly="False" Width="38*">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBox 
                Text="{Binding Path=TheText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
                Template="{DynamicResource TextBoxOfCellsInDataGridOfSubtitle}"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

XML
<ControlTemplate x:Key="TextBoxOfCellsInDataGridOfSubtitle" TargetType="TextBox">
    <TextBox Text="{TemplateBinding Text}"
             AcceptsReturn="False" 
             CaretBrush="White" 
             Foreground="White"
             Background="Transparent"
             BorderBrush="Transparent"
             BorderThickness="0"
             TextAlignment="Center"
             HorizontalAlignment="Stretch"
             HorizontalContentAlignment="Stretch"
             VerticalAlignment="Stretch"
             VerticalContentAlignment="Center"/>
</ControlTemplate>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900