Listbox 获取子控件的问题
当发生SelectionChanged事件时, 想更改以下“img_findme”的图片,尝试了几次都失败了, 上代码求指教
<ListBox x:Name="list_logs" SelectionChanged="Log_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Image x:Name="img_findme" Width="280" Source="{Binding pic}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
private void Log_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Image img_toplay = GetChildObject<Image>(list_logs, "img_findme");//可以方式找到的不是选择项的图片
ListBoxItem boxitem = list_logs.Items[menuListBox.SelectedIndex] as ListBoxItem;
Image img_toplay = GetChildObject<Image>(boxitem, "img_findme");//这种方式找不到,boxitem是null
}
/// <summary>
/// 根据name获取可视子元素
/// </summary>
/// <param name="dependencyObject">当前元素</param>
/// <param name="name">指定子元素名</param>
/// <returns></returns>
public static FrameworkElement FindVisualChildByName(this DependencyObject dependencyObject, String name)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dependencyObject); i++)
{
FrameworkElement childElement = VisualTreeHelper.GetChild(dependencyObject, i) as FrameworkElement;
if (childElement != null && String.Equals(childElement.Name, name, StringComparison.OrdinalIgnoreCase))
{
return childElement;
}
else
{
FrameworkElement childOfChild = FindVisualChildByName(childElement, name);
if (childOfChild != null)
{
return childOfChild;
}
}
}
return null;
}