[英]Accessing Elements or Controls in a UWP ControlTemplate
我有一個繼承自CalendarView元素的XAML UserControl
。 在CalendarViewItemStyle中,我編輯了ControlTemplate來保存Grid和TextBox。
<Style x:Name="CalDayStyle"
TargetType="CalendarViewDayItem">
<Setter Property="Background"
Value="Transparent" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate x:Name="cTemp">
<Grid x:Name="RootGrid"
Background="{TemplateBinding Background}">
<StackPanel x:Name="CalDayStack"
Orientation="Vertical"
VerticalAlignment="Stretch">
<TextBlock x:Name="tasksPres"
TextAlignment="Center"
HorizontalAlignment="Stretch">
</TextBlock>
</StackPanel>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
我試圖訪問TextBox但無濟於事,使用FindName()。 我該怎么辦。
FindName找不到應用模板中定義的名稱。 要在應用模板中查找項目,請使用VisualTreeHelper.GetChild獲取應用的模板根對象。 然后,您可以在該根對象上調用FindName,您將搜索模板的XAML名稱范圍而不是更大的頁面。
如果你想在你的Style
獲得TextBlock
,你應該能夠使用VisualTreeHelper
來獲取它。
對於考試:
public MainPage()
{
this.InitializeComponent();
texts = new List<TextBlock>();
}
private List<TextBlock> texts;
private void Button_Click(object sender, RoutedEventArgs e)
{
IEnumerable<TextBlock> textBlocks = FindVisualChildren<TextBlock>(Mycontrol);
foreach (var textBlock in textBlocks)
{
if (textBlock.Name == "tasksPres")
{
texts.Add(textBlock);
}
}
foreach (var item in texts)
{
item.Text = "11111111111";
}
}
private static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.