[英]how to access a child element dynamically in WPF
在WPF中,我有一個像這樣的結構
<Button>
<Grid>
<!--definitions for 1 row and 2 columns-->
<TextBlock x:Name="t1" Grid.Column="0"/>
<TextBlock x:Name="t2" Grid.Column="1"/>
</Grid>
</Button>
假定具有此結構的Button b
是動態生成的。 如何從Button b
訪問t1
?
編輯澄清:由於t1
位於內Button b
,是有可能改變的內容t1
如果只訪問b
? 沿着b.childGridElement.childTextBlock_t1.Text = "newString"
東西嗎?
這應該適用於您提供的用例:
((TextBlock)b.FindName("t1")).Text = "newString";
您需要為此使用Visual Tree Helper。
定義處理程序擴展方法
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject parent) where T : DependencyObject
{
if (parent != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
// If the available child is not null and is of required Type<T> then return with this child else continue this loop
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
現在在您的XAML中
IEnumerable<TextBlock> textblockes=FindVisualChildren<TextBlock>(b);
foreach (var textblock in textblockes)
{
if (textblock!= null && textblock.Name="t1")
{
//write code for t1 here;
}
if (textblock!= null && textblock.Name="t2")
{
//write code for t2 here;
}
}
在上面的方法中,無論您的樹結構是什么,它都會找到Button b的所有文本塊,然后根據Name屬性可以執行適當的操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.