不能在构造函数中获取ControlTemplate,那样会显示null
UI需要加载窗体,需要一个时间,所以要注意顺序,不能在构造函数中获取ControlTemplate,那样会显示null,可以再窗体load事件以及控件的事件中使用
DataTemplate要注意以上方法是通过遍历item得到的,也就是说如果你的ItemBox,ItemView等等还没加载数据源,即没有item时不能使用,会报null
但是不用getcontrol获取控件, 在构造函数中改绑定的数据是可以更新界面的。



public static childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is childItem)
{
return (childItem)child;
}
else
{
childItem childOfChild = FindVisualChild<childItem>(child);
if (childOfChild != null)
return childOfChild;
}
}
return null;
}
//按控件名 获得ListBox中的控件
public static object getControl(ListBox myListBox,int index,string FindName)
{
try
{
//var el = myListBox.ItemContainerGenerator.ContainerFromItem(myListBox.Items.GetItemAt(index)) as ListBoxItem;
//if (el != null && el is ListBoxItem)
//{
// ListBoxItem myListBoxItem = (ListBoxItem)el;
// ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(myListBoxItem);
// DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
// return myDataTemplate.FindName(FindName, myContentPresenter);
//}
ListBoxItem myListBoxItem = (ListBoxItem)(myListBox.ItemContainerGenerator.ContainerFromItem(myListBox.Items.GetItemAt(index)));
// Getting the currently selected ListBoxItem
// Note that the ListBox must have
// IsSynchronizedWithCurrentItem set to True for this to work
// ListBoxItem myListBoxItem = (ListBoxItem)(myListBox.ItemContainerGenerator.ContainerFromItem(myListBox.Items.CurrentItem));
// Getting the ContentPresenter of myListBoxItem
ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(myListBoxItem);
// Finding textBlock from the DataTemplate that is set on that ContentPresenter
DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
//TextBlock myTextBlock = (TextBlock)myDataTemplate.FindName("textBlock", myContentPresenter);
// Do something to the DataTemplate-generated TextBlock
//MessageBox.Show("The text of the TextBlock of the selected list item: " + myTextBlock.Text);
return myDataTemplate.FindName(FindName, myContentPresenter);
// BindingSettingsClass o = (BindingSettingsClass)(myListBox.Items.GetItemAt(i));
}
catch { }
return null;
}
4万+

被折叠的 条评论
为什么被折叠?



