0

我的xml:

<Style x:Key="grid_image_panel" TargetType="ContentControl">
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <Grid x:Name="image_panel">                       
                    <Image Name="img" Source="Resources/rhcp.jpg" HorizontalAlignment="Center" VerticalAlignment="Center"/>                      
                </Grid>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

我需要在我的 C# 代码隐藏中为图像“img”设置事件“Tap”:

DataTemplate dt = gridy.ContentTemplate as DataTemplate;

DataTemplate dt = gridy.ContentTemplate as DataTemplate;        
Grid grid = dt.LoadContent() as Grid;

Image img = grid.Children.First() as Image;
img.Tap += OnTapped;

结果:点击无效

4

2 回答 2

1

通过使用例如 Loaded Event 来简化事情:

        <DataTemplate>
            <Grid x:Name="image_panel">                       
                <Image Name="img" Loaded=OnImgLoaded Source="Resources/rhcp.jpg" HorizontalAlignment="Center" VerticalAlignment="Center" />                      
            </Grid>
        </DataTemplate>

C#:

private void OnImgLoaded(object sender, RoutedEventArgs e)
    {
         // subscribe to your custom Tap event
         (sender as Image).Tap += OnTapped;
    }

你肯定有类似的东西:

public static readonly RoutedEvent TapEvent = EventManager.RegisterRoutedEvent(
        "Tap",
        RoutingStrategy.Bubble,
        typeof(RoutedEventHandler),
        typeof(MyClass));
于 2013-07-03T08:35:07.657 回答
0

正如文档所说:

当您调用 LoadContent 时,会创建 DataTemplate 中的 UIElement 对象,您可以将它们添加到另一个 UIElement 的可视化树中。

这意味着,对于上面的代码,当您调用时,LoadContent您将获得一组在Template. 相反,您想要的是获取已经加载到您的ContentControl's可视化树中的图像。

你必须得到视觉孩子才能得到你的形象:

Image img = FindVisualChild<Image>(gridy);
img.Tap += OnTapped;

这是FindVisualChild方法:

private childItem FindVisualChild<childItem>(DependencyObject obj)
    where childItem : DependencyObject
{

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
    {

        DependencyObject child = VisualTreeHelper.GetChild(obj, i);

        if (child != null && child is childItem)
            return (childItem)child;
        else
        {
            childItem childOfChild = FindVisualChild<childItem>(child);
            if (childOfChild != null)
               return childOfChild;
        }
    }

    return null;
}
于 2013-07-03T08:37:38.653 回答