我ControlTemplate
在资源字典文件中定义了一个:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ControlTemplate x:Key="ctlTemplate">
<ControlTemplate.Resources>
<StackPanel x:Key="sp" x:Name="sp">
<TextBlock Name="tplTextBlock" HorizontalAlignment="Center"/>
<DataGrid Name="tableBlock" AutoGenerateColumns="False"/>
</StackPanel>
</ControlTemplate.Resources>
</ControlTemplate>
</ResourceDictionary>
我有一个派生自的类,Thumb
我正在尝试将其Template
属性设置为上述ControlTemplate
:
Dim ct As ControlTemplate = CType(Application.Current.Resources("ctlTemplate"), ControlTemplate)
Dim tb As MovableTableBlock = New MovableTableBlock 'Derives from Thumb
tb.Template = ct
tb.UpdateLayout()
问题是Thumb
根本没有渲染。但是,如果我删除了ControlTemplate.Resources
标签,结果也删除了 ,的x:Key
属性。我设置属性的原因是因为我想访问和子项来分别设置文本和数据绑定。基本上我只想访问的孩子。我怎样才能访问它们?StackPanel
Thumb
x:Key
StackPanel
TextBlock
DataGrid
StackPanel
编辑:我已将其更改ControlTemplate
为:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:VQ.Custom">
<Style TargetType="{x:Type local:MovableTableBlock}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:MovableTableBlock}">
<StackPanel x:Name="sp">
<TextBlock x:Name="tplTextBlock" HorizontalAlignment="Center"/>
<DataGrid x:Name="tableBlock" AutoGenerateColumns="False"/>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
所以现在,我不必像这样设置模板:
tb.Template = ct
现在Thumb
渲染了,但我仍然无法按照这里的建议访问内部控件。出于某种原因,tb.Template
当Nothing
我这样做时:
Dim txtBlock As TextBlock = CType(tb.Template.FindName("tplTextBlock", tb), TextBlock)