你好,我是動態地添加自定義控件WPF應用程序。該控件是一個自定義滑塊。我在XAML文件中創建了一個ControlTemplate,我想用它作爲這些動態創建控件的模板。我目前使用應用模板:
newControl.Template = (ControlTemplate)parent.Resources["nameOfTheControlTemplate"];
目前這個工程確定(即編譯,運行和applys模板)。
模板看起來是這樣的:(對不起,文字的牆)
<ControlTemplate x:Key="errorRangeSliderRight" TargetType="{x:Type Slider}">
<Border SnapsToDevicePixels="true" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto" MinHeight="{TemplateBinding MinHeight}"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Track x:Name="PART_Track" Grid.Row="1">
<Track.Thumb>
<Thumb x:Name="Thumb" HorizontalContentAlignment="Right" Width="7">
<Thumb.Template>
<ControlTemplate TargetType="Thumb">
<Path x:Name="nameOfPath" Stroke="Black" StrokeThickness="0" Fill="Red">
<Path.Data>
<GeometryGroup FillRule="NonZero">
<PathGeometry>
<PathGeometry.Figures>
<PathFigure IsClosed="True" StartPoint="7,150">
<PathFigure.Segments>
<PathSegmentCollection>
<LineSegment Point="5,150" />
<LineSegment Point="5,0" />
<LineSegment Point="7,0" />
</PathSegmentCollection>
</PathFigure.Segments>
</PathFigure>
<PathFigure IsClosed="True" StartPoint="0,75">
<PathFigure.Segments>
<PathSegmentCollection>
<LineSegment Point="7,70" />
<LineSegment Point="7,80" />
<LineSegment Point="0,75" />
</PathSegmentCollection>
</PathFigure.Segments>
</PathFigure>
</PathGeometry.Figures>
</PathGeometry>
</GeometryGroup>
</Path.Data>
</Path>
</ControlTemplate>
</Thumb.Template>
</Thumb>
</Track.Thumb>
</Track>
</Grid>
</Border>
</ControlTemplate>
推理:
我爲什麼選擇來定義XAML控件模板,而不是動態創建的原因使用FrameworkElementFactory的數百萬行代碼的模板是因爲它更簡單,更清潔,更易於維護/讀取。
我想要什麼:
我想使控件模板內的輕微改動此對照模板(僅Path對象的填充顏色)。如果可能,我想獲得對ControlTemplate對象的引用。
我曾嘗試:
我試圖調用該模板的FindName(「nameOfPath」),它返回一個空對象。
Object o = newControl.Template.FindName("nameOfPath",newControl);
我曾嘗試創建使用大量FrameworkElementFactory實例和構建的ControlTemplate這樣的ContentTemlpate,這是不成功的(該控件模板對象是相當複雜的,有許多子元素)。
+1只是爲了具有這樣的精心佈置的問題 – mydogisbox