在文本框数据网格 WPF 中使用控件模板并绑定在一起时出错


嗨,我有一个数据网格。 我在其单元格中使用了 TextBox。
我为它做了一个ControlTemplate。
所以我的问题是当我使用 controlTemplate 时,TextBox 的绑定将不起作用。 但是,如果我直接在 DataTemplate 中设置所有内容,则绑定效果完美。
有什么想法吗?

我尝试过的:

在此代码中绑定到 TextBox 效果非常好:

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>

绑定到 TextBox 在此代码中不起作用! :

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>

解决方案1

我找到了答案。
我应该将文本绑定到父级,然后绑定到类。

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>

コメント

タイトルとURLをコピーしました