DataGridTemplateColumn 单元格的 WPF 内容
在 WPF 中,我引用了 DataGridCell 并希望获取其内容。我曾经将该单元格放在 DataGridTextColumn 中,并且可以获取如下内容:
var text = cell.Content as TextBlock;
但这不再起作用,因为单元格位于 DataGridTemplateColumn 中,尽管我确实指定 TextBlock 作为该列的 DataTemplate。还有办法得到它吗?
编辑以澄清问题。以下代码按预期工作:
<!-- 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
但是,如果我使用 TemplateColumn,则代码将不起作用,因为块将为空。
<DataGridTemplateColumn Header="Autor" Width="*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Name="txtAutor" Text="{Binding Author}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
有没有办法仍然获取单元格内容(在我的例子中是一个字符串)?
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)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该能够为
DataTemplate
内的TextBlock
命名,然后使用Text
属性来获取数据。You should be able to give your
TextBlock
inside theDataTemplate
a name, and then use theText
property to get the data.