我有一个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;
答案 0 :(得分:0)
ControlTemplate.FindName
才会返回Item。如果您在UserControl
中执行此操作,则可以通过覆盖OnApplyTemplate
来获取此信息。或者,如果您在UserControl
之外,您可以使用Control.Loaded事件:)
希望它有所帮助:)