C# 访问UWP ControlTemplate中的元素或控件
我有一个从CalendarView元素继承的XAMLC# 访问UWP ControlTemplate中的元素或控件,c#,xaml,uwp,C#,Xaml,Uwp,我有一个从CalendarView元素继承的XAMLUserControl。在CalendarViewItemStyle中,我编辑了ControlTemplate以保存网格和文本框 <Style x:Name="CalDayStyle" TargetType="CalendarViewDayItem"> <Setter Property="Background" Value="Transparent" /&g
UserControl
。在CalendarViewItemStyle中,我编辑了ControlTemplate以保存网格和文本框
<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>
我正在尝试使用FindName()访问文本框,但无效。我该怎么办
FindName找不到在应用的模板中定义的名称。要在应用的模板中查找项,请使用VisualTreeHelper.GetChild获取应用的模板根对象。然后可以在该根对象上调用FindName,您将搜索模板的XAML名称范围,而不是更大的页面
如果您想以样式获取文本块
,您应该能够使用来获取它
例如:
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;
}
}
}
}
public主页()
{
this.InitializeComponent();
文本=新列表();
}
私人清单文本;
私有无效按钮\u单击(对象发送者,路由目标e)
{
IEnumerable textBlocks=FindVisualChildren(Mycontrol);
foreach(textBlocks中的var textBlock)
{
if(textBlock.Name==“tasksPres”)
{
text.Add(textBlock);
}
}
foreach(文本中的var项)
{
item.Text=“11111111”;
}
}
私有静态IEnumerable FindVisualChildren(DependencyObject depObj),其中T:DependencyObject
{
if(depObj!=null)
{
for(int i=0;i
我不认为您可以像那样获取TextBlock数据,您需要创建一个DependencyObject
,然后将其绑定到TextBlock
Text,这样您就可以从注释中的UserControl
中获取该值,您将在模板的根子级上使用FindName,但是在示例代码中,您做了一些完全不同的事情。