Search code examples
.netwpfxamldatatemplatecode-behind

Change element property in code-behind, that described in xaml, DataTemplate


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

I need set event "Tap" for Image "img" in code-behind My 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;

Result: tap not worked


Solution

  • ease up things by using e.g. 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;
        }
    

    you sure have something like:

    public static readonly RoutedEvent TapEvent = EventManager.RegisterRoutedEvent(
            "Tap",
            RoutingStrategy.Bubble,
            typeof(RoutedEventHandler),
            typeof(MyClass));