WPF contents of cell of DataGridTemplateColumn

∥☆過路亽.° 提交于 2019-12-12 02:00:59

问题


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:


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;


来源:https://stackoverflow.com/questions/6840344/wpf-contents-of-cell-of-datagridtemplatecolumn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!