WPF contents of cell of DataGridTemplateColumn

2019-09-09 06:22发布

In WPF I have the reference to a DataGridCell and would like to get its contents. I used to have that cell in a DataGridTextColumn and could get at the content like this:

var text = cell.Content as TextBlock;

But this is not longer working since the cell is in a DataGridTemplateColumn, although I did specify TextBlock as the DataTemplate for that column. Is there still a way to get at it?

EDIT to clarify the problem. The following code is working as intended:

<!-- XAML -->
<DataGridTextColumn Header="Autor" Width="*"  Binding="{Binding Author}" />

//C#
var block = _selectedCell.Content as TextBlock;
var text = block.Text; //text contains the string that is also displayed by the grid in that call

If I however use a TemplateColumn the code will not work because block will be null.

<DataGridTemplateColumn Header="Autor" Width="*">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Name="txtAutor" Text="{Binding Author}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

Is there a way to still get at the cells contents (a string in my case)?

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-09-09 06:55

You should be able to give your TextBlock inside the DataTemplate a name, and then use the Text property to get the data.

<DataTemplate>
    <TextBlock Name="txtData" Text="{Binding}" />
</DataTemplate>

var text = txtData.Text as string;
查看更多
登录 后发表回答