我有一个字符串名称的ObservableCollection,它被设置为ListBox的ItemsSource. ListBox中按钮的名称是什么.然后我想从ListBox中提取按钮,但返回值是string类型.
xaml代码是:
<ListBox x:name="Game_ScrollVIEwer_online" margin="41,104,128,6" SelectedValuePath="Current_game_button"> <ListBox.ItemTemplate> <DataTemplate> <button x:name="Current_game_button" Content="{Binding}" HorizontalAlignment="Center" Height="80" margin="-14,6,-15,0" VerticalAlignment="top" WIDth="210" Template="{StaticResource button_CurrentLayout1}" RendertransformOrigin="0.5,0.5" Foreground="#FFCBECCB" FontFamily="Times New Roman" Click="LoadGame_online" FontSize="16"> </button> </DataTemplate> </ListBox.ItemTemplate></ListBox>
然后我想要提取按钮元素:
for (int i = 0; i < Game_ScrollVIEwer_online.Items.Count; i++){ var tempType = Game_ScrollVIEwer_online.Items[i].GetType(); button tempBut = (Game_ScrollVIEwer_online.Items[i] as button); //Do stuff with button}
但正如所说的返回类型是字符串.
为什么不是按钮?有没有办法访问按钮?
解决方法 你需要FrameworkTemplate.FindName Method (String, FrameworkElement)
用于此目的: private 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;}
然后:
for (int i = 0; i < Game_ScrollVIEwer_online.Items.Count; i++){ ListBoxItem GameListBoxItem = (ListBoxItem)(Game_ScrollVIEwer_online.ItemContainerGenerator.ContainerFromIndex(i)); ContentPresenter contentPresenter = FindVisualChild<ContentPresenter>(GameListBoxItem); DataTemplate myDataTemplate = contentPresenter.ContentTemplate; button tempBut = (button) myDataTemplate.Findname("Current_game_button",contentPresenter); //Do stuff with button}
要解决缺少的Findname,请使用FindDescendant,如下所示:
public T FindDescendant<T>(DependencyObject obj) where T : DependencyObject{ if (obj is T) return obj as T; int childrenCount = VisualTreeHelper.GetChildrenCount(obj); if (childrenCount < 1) return null; for (int i = 0; i < childrenCount; i++) { DependencyObject child = VisualTreeHelper.GetChild(obj,i); if (child is T) return child as T; } for (int i = 0; i < childrenCount; i++) { DependencyObject child = FindDescendant<T>(VisualTreeHelper.GetChild(obj,i)); if (child != null && child is T) return child as T; } return null;}总结
以上是内存溢出为你收集整理的c# – 当DataTemplate为Button时,ListBox项返回字符串全部内容,希望文章能够帮你解决c# – 当DataTemplate为Button时,ListBox项返回字符串所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)