WPF 获取ControlTemplate 中的控件方法
1 CheckBox cbSelect = (CheckBox)(ListBoxView.Items[i] as ListBoxItem).Template.FindName("cbSelect", ListBoxView.Items[i] as ListBoxItem);
2 TextBlock textblackConnPointNum = (TextBlock)(ListBoxView.Items[i] as ListBoxItem).Template.FindName("textblackConnPointNum", ListBoxView.Items[i] as ListBoxItem);
3 TextBlock textblackConnPointNam = (TextBlock)(ListBoxView.Items[i] as ListBoxItem).Template.FindName("textblackConnPointName", ListBoxView.Items[i] as ListBoxItem);
4 ComboBox cbGroup = (ComboBox)(ListBoxView.Items[i] as ListBoxItem).Template.FindName("cbGroup", ListBoxView.Items[i] as ListBoxItem);
5 CheckBox cbPublic = (CheckBox)(ListBoxView.Items[i] as ListBoxItem).Template.FindName("cbPublic", ListBoxView.Items[i] as ListBoxItem);
对应着xaml:
1 <ContentControl>
2 <Grid>
3 <CheckBox Name="cbSelect" Margin="2,0,0,0" VerticalAlignment="Center" IsChecked="{Binding IsSelected, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}" <ContentPresenter Margin="2"/>
4 5 <TextBlock Width="80" Name="textblackConnPointNum" TextAlignment="Center" Text="{Binding Path=ConnPointNum}"/>
6 <TextBlock Width="150" Name="textblackConnPointName" Text="{Binding Path=ConnPointName}" TextAlignment="Center"/>
7 ......
8 </Grid>
9 </ContentControl>
在ControlTemplate中找控件最重要的就是让控件初始化到visualtree上,所以如何没有找到ControlTemplate的控件就有可能是控件还未能加载到visualtree。
可以用一下两种方式强制刷新模板控件至visualtree.
第一种是UpdateLayout() 方法。
但是MSDN提示:如果 UI 中存在大量元素,则频繁调用 InvalidateArrange(尤其是频繁调用 UpdateLayout)将会对性能产生重大影响。除非代码中后续调用其他 API 绝对需要精确的布局状态,否则请避免调用此方法。
第二种方案:
private delegate void NoArgDelegate();
public static void Refresh(DependencyObject obj)
{
obj.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.ApplicationIdle, (NoArgDelegate)delegate { });
}