2014-07-11 44 views
0

我已经在列表框中为我的ListBoxItem创建了一个控件模板,并且每个ListBoxItem都由contentpresenter和一个图像组成。通过点击列表框中的特定元素来查找列表框

我对你的问题是......我怎么知道,当我点击列表框中的图像时,我点击了哪个列表框。

<Style x:Key="ListBoxItemWithDelete" TargetType="ListBoxItem"> 
      <Setter Property="Template"> 
       <Setter.Value> 
        <ControlTemplate TargetType="ListBoxItem"> 
         <Border Name="Border" Padding="2" SnapsToDevicePixels="true"> 
          <Grid> 
           <ContentPresenter VerticalAlignment="Center" /> 
           <Image Name="ImageListItemDelete" Source="../Resources/Images/actions-delete-big-1.png" Width="20" Style="{StaticResource MenuItemIcon}" HorizontalAlignment="Right" 
           MouseLeftButtonUp="ImageListItemDelete_MouseLeftButtonUp"/> 
          </Grid> 
         </Border> 
         <ControlTemplate.Triggers> 
          <Trigger Property="IsSelected" Value="true"> 
           <Setter TargetName="Border" Property="Background" Value="{StaticResource SelectedBackgroundBrush}"/> 
          </Trigger> 
          <Trigger Property="IsEnabled" Value="false"> 
           <Setter Property="Foreground" Value="{StaticResource DisabledForegroundBrush}"/> 
          </Trigger> 
         </ControlTemplate.Triggers> 
        </ControlTemplate> 
       </Setter.Value> 
      </Setter> 
     </Style> 

private void ImageListItemDelete_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) 
{ 
    //Object sender is my Image i Clicked. 
    if (ListBoxName.SelectedItem != null) 
    { 
    ListBoxName.Items.Remove(ListBoxName.SelectedItem); 
    } 
} 

我想用包含这个图像的列表框替换ListBoxName,我点击了,现在“ListBoxName”是硬编码的。

我知道如何通过listboxitems找到他们的内容模板,但我不知道如何以相反的方式工作。 :/

回答

0

找到某个特定类型的UIElement的祖先的更好方法是使用VisualTreeHelper class。从链接页面:

提供执行涉及视觉树中节点的常见任务的实用方法。

您可以使用此辅助方法来找到你的ListBox

public T GetParentOfType<T>(DependencyObject element) where T : DependencyObject 
{ 
    Type type = typeof(T); 
    if (element == null) return null; 
    DependencyObject parent = VisualTreeHelper.GetParent(element); 
    if (parent == null && ((FrameworkElement)element).Parent is DependencyObject) 
     parent = ((FrameworkElement)element).Parent; 
    if (parent == null) return null; 
    else if (parent.GetType() == type || parent.GetType().IsSubclassOf(type)) 
     return parent as T; 
    return GetParentOfType<T>(parent); 
} 

你会使用这样的:

ListBox listBox = GetParentOfType<ListBox>(sender as UIElement); 
+0

谢谢..这正是我正在寻找的。我知道另一个通过子元素向下穿过的人。 –

0

你得到的回答却也未必总是如此,由于模板的差异,通过可视化树或逻辑树,所以寻找将是适当的

例如

public static T FindAncestor<T>(DependencyObject dependencyObject) where T : class 
{ 
    DependencyObject target = dependencyObject; 
    do 
    { 
     target = VisualTreeHelper.GetParent(target); 
    } 
    while (target != null && !(target is T)); 
    return target as T; 
} 

使用

ListBox listBox = FindAncestor<ListBox>(sender as DependencyObject); 

更复杂的例子在这里Finding an ancestor of a WPF dependency object

+0

谢谢您的回答,我其实是寻找类似这而不是我自己的例子。 –

相关问题