通过c#

时间:2015-10-14 19:50:46

标签: wpf xaml controltemplate

我有一个wpf应用程序,我在App.xaml中有ControlTemplate。此ControlTemplate包含Grid和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>

我需要帮助从mainWindow.xaml.cs访问此ControlTemplate中的Grid和Canvas。 我想改变attribut&#34; Visibility&#34;当它在PropertyChanged或ViewChangeEnd事件时。

我尝试过但不起作用。

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

甚至这个

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

1 个答案:

答案 0 :(得分:0)

只有在控件上应用模板后,

ControlTemplate.FindName才会返回Item。如果您在UserControl中执行此操作,则可以通过覆盖OnApplyTemplate来获取此信息。或者,如果您在UserControl之外,您可以使用Control.Loaded事件:) 希望它有所帮助:)