UWP 查找模板中的控件
这个标题我也不知道咋起,意思说一下你就明白。
1. 对官方控件的模板进行定制修改,以满足多样化需求,还有漂亮的UI
比如ListView,GridView等。
2. 在设计的情况下并没有这个控件,而在运行时的时候出现了它
比如微软的广告组件,他们叫AdControl,在运行时其实就是一个WebView
下面看一下我的实际项目中的代码,来举例说明:
<FlipView x:Name="flipView" Background="{ThemeResource SystemControlChromeMediumAcrylicWindowMediumBrush }">
<FlipView.ItemTemplate> <DataTemplate> <Grid> <Image x:Name="myImage" Grid.RowSpan="3" Stretch="Uniform" Source="{Binding img_realurl}" IsDoubleTapEnabled="True" DoubleTapped="detailImage_DoubleTapped"/> <TextBlock Text="{Binding sitename}" Margin="3,0,0,0" VerticalAlignment="Center" Foreground="{ThemeResource SystemControlBackgroundAccentBrush}"/> </StackPanel> </Grid> </DataTemplate> </FlipView.ItemTemplate> </FlipView>
我这个是定义的FlipView的模板,大家可以发现,里面用到个Image控件,而这个控件,你如果直接定义他的x:Name的话,在后台代码.cs里面使用myImage,是识别不到的。微软不让这么用。
那么怎么办,就是需要在运行时,通过代码查找他,然后再操作即可。
查找的方法如下:
public static T MyFindListBoxChildOfType<T>(DependencyObject root) where T : class { var MyQueue = new Queue<DependencyObject>(); MyQueue.Enqueue(root); while (MyQueue.Count > 0) { DependencyObject current = MyQueue.Dequeue(); for (int i = 0; i < VisualTreeHelper.GetChildrenCount(current); i++) { var child = VisualTreeHelper.GetChild(current, i); var typedChild = child as T; if (typedChild != null) { return typedChild; } MyQueue.Enqueue(child); } } return null; }
然后在页面加载完成的事件里面使用,
private void Page_Loaded(object sender, RoutedEventArgs e) { Image headImage = MyFindListBoxChildOfType<Image>(flipView); headImage.PointerEntered += Head_PointerEntered; headImage.PointerExited += Head_PointerExited; }
记下来就可以为所欲为的操作了。
有人说,我们的模板里有多个Image控件,咋办?
你将查找的函数改成返回List<T>即可,然后在Looaded里面按顺序取即可。
private void Page_Loaded(object sender, RoutedEventArgs e) { Image detailImage = MyFindListBoxChildOfType<Image>(flipView)[0]; Image headImage = MyFindListBoxChildOfType<Image>(flipView)[1]; }
这个顺序就是你在Xaml里面写的顺序。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)