【问题标题】:How to access Image from TextBlock from codebehind?如何从代码隐藏中访问 TextBlock 中的图像?
【发布时间】:2014-07-29 11:57:33
【问题描述】:

对于以下 XAML,我如何从 TextBlock 的代码隐藏中访问图像?

<TextBlock Name="btnRating5" PreviewMouseDown="btnRating5_PreviewMouseDown"
           Tag="{Binding ID}" Margin="5,0,0,0" Padding="1">
<Image Source="{Binding Rating, Mode=OneTime, Converter={StaticResource MyImagePathConverter}}" />
</TextBlock>

【问题讨论】:

  • 为什么需要“访问”那个 UI 元素?它已经 DataBound 到基础数据项。无论您需要做什么,都应该通过 DataBinding 而不是程序代码来完成。

标签: .net wpf


【解决方案1】:

您可以使用VisualTreeHelper 类来获取任何控件的子级。

假设你想在 TextBlock 的 PreviewMouseDown 事件中找到图片,那么你可以这样做:

private void btnRating5_PreviewKeyDown(object sender, ....... e)
{
    var containerVisual = VisualTreeHelper.GetChild((TextBlock)sender, 0) as ContainerVisual;
    Image myImage = containerVisual .Children[0] as Image;
}

如果代码不起作用,请尝试将索引从 0 更改为 1。

如果您有任何问题,请告诉我:)。

【讨论】:

    猜你喜欢
    • 2010-11-01
    • 2011-04-23
    • 2014-10-29
    • 2017-10-04
    • 1970-01-01
    • 1970-01-01
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多