UWP 查找模板中的控件
生活随笔
收集整理的這篇文章主要介紹了
UWP 查找模板中的控件
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
UWP 查找模板中的控件 原文:UWP 查找模板中的控件
<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>
這個標題我也不知道咋起,意思說一下你就明白。
1. 對官方控件的模板進行定制修改,以滿足多樣化需求,還有漂亮的UI
比如ListView,GridView等。
2. 在設計的情況下并沒有這個控件,而在運行時的時候出現(xiàn)了它
比如微軟的廣告組件,他們叫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的模板,大家可以發(fā)現(xiàn),里面用到個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控件,咋辦?
你將查找的函數(shù)改成返回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未來之路 閱讀(...) 評論(...) 編輯 收藏轉(zhuǎn)載于:https://www.cnblogs.com/lonelyxmas/p/9405026.html
總結(jié)
以上是生活随笔為你收集整理的UWP 查找模板中的控件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: “猜画小歌”的一些细节和思考
- 下一篇: Windows下phpStudy中的Ap