如何:尋找 ControlTemplate 產生的項目
此範例示範如何尋找 所產生的 ControlTemplate 專案。
範例
下列範例顯示一種樣式,可建立 類別的 Button 簡單 ControlTemplate :
<Style TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid Margin="5" Name="grid">
<Ellipse Stroke="DarkBlue" StrokeThickness="2">
<Ellipse.Fill>
<RadialGradientBrush Center="0.3,0.2" RadiusX="0.5" RadiusY="0.5">
<GradientStop Color="Azure" Offset="0.1" />
<GradientStop Color="CornflowerBlue" Offset="1.1" />
</RadialGradientBrush>
</Ellipse.Fill>
</Ellipse>
<ContentPresenter Name="content" Margin="10"
HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
若要在套用範本之後在範本內尋找專案,您可以呼叫 FindName 的 Template 方法。 下列範例會建立訊息方塊,顯示控制項範本內 的實際寬度值 Grid :
// Finding the grid that is generated by the ControlTemplate of the Button
Grid gridInTemplate = (Grid)myButton1.Template.FindName("grid", myButton1);
// Do something to the ControlTemplate-generated grid
MessageBox.Show("The actual width of the grid in the ControlTemplate: "
+ gridInTemplate.GetValue(Grid.ActualWidthProperty).ToString());
' Finding the grid that is generated by the ControlTemplate of the Button
Dim gridInTemplate As Grid = CType(myButton1.Template.FindName("grid", myButton1), Grid)
' Do something to the ControlTemplate-generated grid
MessageBox.Show("The actual width of the grid in the ControlTemplate: " & gridInTemplate.GetValue(Grid.ActualWidthProperty).ToString())
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應