欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

UWP 查找模板中的控件

发布时间:2025/7/25 72 豆豆
生活随笔 收集整理的这篇文章主要介绍了 UWP 查找模板中的控件 小编觉得挺不错的,现在分享给大家,帮大家做个参考.
UWP 查找模板中的控件 原文: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里面写的顺序。

 

posted on 2018-08-02 08:24 NET未来之路 阅读(...) 评论(...) 编辑 收藏

转载于:https://www.cnblogs.com/lonelyxmas/p/9405026.html

总结

以上是生活随笔为你收集整理的UWP 查找模板中的控件的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。