2009-08-26 4 views
2

사용자가 주어진 ListBox 항목을 한 번 클릭 할 때 일부 코드를 실행하고 싶습니다. 제 설정은 ItemsPanelTemplate (Pavan 's ElementFlow) 사용자 정의 ListBox입니다. MouseLeftButtonDown에 오는 위치 데이터를 기반으로 클릭 한 항목을 알 수있는 방법이 있습니까? 이것은 사용자 정의 ItemsPanelTemplate에 의해 조금 더 어렵거나 혼란스럽게 만들어집니다.MouseLeftButtonDown에서 WPF ListBox 항목 가져 오기

답변

11

당신은 ItemContainerStyle을하고있는 EventSetter 지정할 수 있습니다

<ListBox> 
    <ListBox.ItemContainerStyle> 
     <Style TargetType="{x:Type ListBoxItem}"> 
      <EventSetter Event="MouseLeftButtonDown" Handler="ListBoxItem_MouseLeftButtonDown" /> 
    ... 

는 다음, MouseLeftButtonDown의 핸들러에서 "보낸 사람"이 ListBoxItem의 것입니다. 이 방법을 사용하지 않으려면

또한, 당신은 지정된 위치에있는 시각적 객체를 찾을 그러나 hitTest를 호출 할 수

HitTestResult result = VisualTreeHelper.HitTest(myCanvas, pt); 

ListBoxItem lbi = FindParent<ListBoxItem>(result.VisualHit); 

public static T FindParent<T>(DependencyObject from) 
    where T : class 
{ 
    T result = null; 
    DependencyObject parent = VisualTreeHelper.GetParent(from); 

    if (parent is T) 
     result = parent as T; 
    else if (parent != null) 
     result = FindParent<T>(parent); 

    return result; 
} 
+0

을 와우, 완벽하게! 하지만 그것은 {x : Type ListBoxItem} 대신 사용해야합니다. – Mike

+0

감사합니다. 나는 그것을 고쳤다. – decasteljau