![](/img/trans.png)
[英]How to get a reference to a control within a ControlTemplate outside its ControlTemplate?
[英]How to Reference Template of Control within ControlTemplate
我想從擴展WPF工具包中設置DateTimePicker的樣式有所不同,尤其是Calendar控件。
<ControlTemplate x:Key="DatePickerTemplate" TargetType="{x:Type xctk:DateTimePicker}">
...
<Calendar x:Name="PART_Calendar" Template="{StaticResource CalendarTemplate}" BorderThickness="0" DisplayDate="2014-05-14"/>"
...
</ControlTemplate>
為了使我能夠在上面的代碼中引用下面的控件模板(兩者都在同一文件中),有什么必要?
<ControlTemplate x:Key="CalendarTemplate" TargetType="Calendar">
<StackPanel x:Name="Root" HorizontalAlignment="Center">
<CalendarItem x:Name="CalendarItem" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Template="{StaticResource CalendarItemTemplate}"/>
</StackPanel>
</ControlTemplate>
目前,VS抱怨:無法解決資源“ CalendarTemplate”。
更新:更改定義的順序后,因此首先定義<ControlTemplate x:Key="CalendarTemplate" TargetType="Calendar">...
然后使用CalendarTemplate
的ControlTemplate起作用,使我想起了c ++,但現在我得到了以下內容如果我嘗試打開日歷控件,則為異常:
Add value to dictionary of type 'System.Windows.ResourceDictionary' threw an exception.
您所指的是StaticResource,因此應聲明CalendarTemplate為x:Key而不是x:Name即
<ControlTemplate x:Key="CalendarTemplate" TargetType="Calendar">
...
</ControlTemplate>
更新以顯示類似的工作方式(請注意,它們在我的Xaml文件的同一級別上定義,即都在我的主要Views資源下)
<ControlTemplate x:Key="ABC123" TargetType="Button">
</ControlTemplate>
<!-- creating a control template for TextBox -->
<ControlTemplate x:Key="PasswordBoxTemplateBase" TargetType="{x:Type PasswordBox}">
<Grid x:Name="root" Height="{TemplateBinding Height}" Width="{TemplateBinding Width}">
<Border x:Name="normalBorder"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"/>
<Button Template="{StaticResource ABC123}"/>
</Border>
</Grid>
</ControlTemplate>
問題是在StaticResource而不是x:Key上使用x:Name 。 應該是這樣的( x:Key =“ CalendarTemplate” ):
<ControlTemplate x:Key="CalendarTemplate" TargetType="Calendar">
</ControlTemplate>
<ControlTemplate x:Key="DatePickerTemplate" TargetType="DatePicker">
<Calendar x:Name="PART_Calendar" Template="{StaticResource CalendarTemplate}" BorderThickness="0"/>
</ControlTemplate>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.