更改代码隐藏中的元素属性,在xaml,DataTemplate中描述

时间:2013-07-03 06:10:02

标签: .net wpf xaml datatemplate code-behind

我的xaml:

<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>

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

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;

结果:点击无效

2 个答案:

答案 0 :(得分:1)

通过使用例如加载事件:

        <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));

答案 1 :(得分:0)

正如文档所说:

  

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

这意味着,对于上面的代码,当您致电LoadContent时,您将获得Template中定义的一组新UIElements。您想要的是获取已加载到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;
}