B.j
B.j

Reputation: 59

Accessing elements inside ControlTemplate xaml by c#

I have a wpf application there i have ControlTemplate in the App.xaml. This ControlTemplate contains Grid and Then Canvas.

<Application.Resources>
    <ControlTemplate x:Key="PinTemplate" TargetType="m:Pushpin">
        <Grid x:Name="grid2" HorizontalAlignment="left"  VerticalAlignment="Center"   >
            <Canvas x:Name="ContentPopup" Visibility="{TemplateBinding Visibility}">
                <StackPanel  x:Name="stackPanel1" Canvas.Left="0" Canvas.Top="-20"  Visibility="{TemplateBinding Visibility}">
                    <ContentPresenter HorizontalAlignment="Center"
                                                            VerticalAlignment="Center"
                                                            Content="{TemplateBinding Content}"

                                                            Margin="0" TextBlock.FontFamily="Segoe UI" TextBlock.FontWeight="Bold" TextBlock.FontSize="10" TextBlock.Foreground="Blue">
                    </ContentPresenter>
                </StackPanel>
            </Canvas>
            <Canvas>
                <Ellipse Name="Ellips12" Fill="AliceBlue" Opacity="0.7" Stroke="Red" StrokeThickness="2"  Height="25" Stretch="Fill" Canvas.Top="5" Width="25"     />
                <TextBlock Text="{TemplateBinding ContentStringFormat }" TextBlock.Foreground="Blue" FontSize="13" TextBlock.TextAlignment="Right"  Margin="10,7,10,0">
                </TextBlock>
            </Canvas>
        </Grid>
    </ControlTemplate>
</Application.Resources>

I need help to access the Grid and the Canvas inside this ControlTemplate from the mainWindow.xaml.cs. I want to change the attribut "Visibility" for it when PropertyChanged or when ViewChangeEnd event.

that what i have tried but doesnt work.

        ControlTemplate ct = Application.Current.Resources["PinTemplate"] as ControlTemplate;
        Grid gr = ct.Resources["grid2"] as Grid;
        gr.Visibility = Visibility.Collapsed;

and even this

 ControlTemplate ct = Application.Current.Resources["PinTemplate"] as ControlTemplate;
        Grid gr = ct.FindName("grid2", this) as Grid;

Upvotes: 0

Views: 838

Answers (1)

fahimalizain
fahimalizain

Reputation: 854

ControlTemplate.FindName returns the Item only after the template is applied on the control. If you are doing this in UserControl you could get it by overriding OnApplyTemplate. Or if you are outside the UserControl you could use Control.Loaded Event for the same :) hope it helped :)

Upvotes: 0

Related Questions