DataGridTemplateColumn 单元格的 WPF 内容

发布于 2024-11-26 13:09:16 字数 981 浏览 3 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烟雨凡馨 2024-12-03 13:09:16

您应该能够为 DataTemplate 内的 TextBlock 命名,然后使用 Text 属性来获取数据。

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

var text = txtData.Text as string;

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;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文