例子1 :需要获得 ListBox 中的 Canvas
<ListBox x:Name="theListBox">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<Canvas Loaded="Canvas_Loaded"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
方法1:Loaded 事件
private Canvas theCanvas = null;
private void Canvas_Loaded(object sender, RoutedEventArgs e)
{
theCanvas = sender as Canvas;
}
方法2:
DependencyObject child = VisualTreeHelper.GetChild(theListBox, 0);
if (!(child is Canvas))
return;
theCanvas = VisualTreeHelper.GetChild(child, 0) as Canvas;
例子2:想获取一个可编辑的 ComboBox 中的 TextBox (顺便说一句,如果不可编辑,则是个 TextBlock,可以使用 SNOOP 来观察)
可编辑的ComboBox含有一个TextBox
<ComboBox x:Name="MyComboBox"
ItemsSource="{Binding X1}"
SelectedItem="{Binding X2}"
SelectedValuePath="X3"
DisplayMemberPath="X4"
Focusable="True"
IsEditable="True"
Loaded="MyComboBox_Loaded"
/>
使用VisualTreeHelper找到TextBox
private object FindFirstChild<T>(DependencyObject p)
{
if (p == null)
return null;
int cnt = VisualTreeHelper.GetChildrenCount(p);
for (int i = 0; i < cnt; ++i)
{
DependencyObject thisLevelChild = VisualTreeHelper.GetChild(p, i);
if (thisLevelChild is T)
return thisLevelChild;
else
{
object obj = FindFirstChild<T>(thisLevelChild); // go to deeper level
if (obj != null)
return obj;
}
}
return null;
}
private TextBox theTextBox = null;
private void MyComboBox_Loaded(object sender, RoutedEventArgs e)
{
ComboBox bx = sender as ComboBox;
object t = FindFirstChild<TextBox>(bx);
if (t != null)
{
theTextBox = t as TextBox;
theTextBox.TextChanged += new TextChangedEventHandler(theTextBox_TextChanged);
}
}
void theTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox bx = sender as TextBox;
string txt = bx.Text;
}