我想获得一个元素(路径),它是我的内容控件的模板。我希望得到" contour_forme"但在互联网上找到的每个解决方案都返回null。我尝试重写OnApplyTemplate但仍然为null:
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
var template = this.pion_test.Template;
var contour = GetTemplateChild("contour_forme");
forme_path = template.FindName("contour_forme", this.pion_test) as Path;
Path path = FindVisualChild<Path>(this.pion_test);
var test = this.pion_test.FindName("contour_forme");
var test2 = this.pion_test.Template.FindName("contour_forme", this.pion_test);
}
我的xaml:
<UserControl.Resources>
<Style TargetType="{x:Type ContentControl}" x:Key="StylePion">
<Setter Property="BorderBrush" Value="Black"/>
<Setter Property="Background" Value="White" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ContentControl">
<Grid Width="33" Height="34">
<Path x:Name="contour_forme"
Stroke="{TemplateBinding BorderBrush}"
StrokeThickness="1"
Stretch="Uniform"
Width="28"
HorizontalAlignment="Left"
Margin="0,-1,0,0"
RenderTransformOrigin="0.59,0.5"
Fill="{TemplateBinding Background}"
Data="M17.36,24.623c-2.142-0.006-4.153-0.552-5.907-1.506l0,0l-0.076-0.046
c-1.952-1.08-3.57-2.673-4.692-4.589L0,11.942l7.126-6.514c1.077-1.584,2.519-2.896,4.2-3.84l0.127-0.077l0,0
C13.23,0.544,15.27-0.006,17.441,0c6.844z"
Tag="{TemplateBinding Tag}"
>
<Path.RenderTransform>
<RotateTransform Angle="50"/>
</Path.RenderTransform>
</Path>
<Ellipse Width="21" Height="21" VerticalAlignment="Center"
HorizontalAlignment="Center"
Fill="{TemplateBinding Background}"
/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<Grid Name="grid_pion">
<ContentControl Name="pion_test" HorizontalAlignment="Center" VerticalAlignment="Center" Tag="4" Content="5" Style="{StaticResource StylePion}" >
</ContentControl>
</Grid>
我想找到一个参考来设置旋转变换。
我做错了什么?
答案 0 :(得分:2)
似乎OnApplyTemplate
适用于UserControl
而不是ContentControl
您可以编写如下自定义控件:
public class MyControl : ContentControl
{
public MyControl()
{
DefaultStyleKey = typeof(MyControl);
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
var template = this.pion_test.Template;
var contour = GetTemplateChild("contour_forme");
forme_path = template.FindName("contour_forme", this.pion_test) as Path;
Path path = FindVisualChild<Path>(this.pion_test);
var test = this.pion_test.FindName("contour_forme");
var test2 = this.pion_test.Template.FindName("contour_forme", this.pion_test);
}
}
和模板:
<Style TargetType="{x:Type MyControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="MyControl">
.....
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>