2009-12-10 28 views
5

Tôi muốn biết liệu chức năng nhấp đúp cho một ListBox có thể dễ dàng xây dựng không. Tôi có một số ListBox với bộ sưu tập là ItemSource. Bộ sưu tập chứa các kiểu dữ liệu riêng.ListBox với DoubleClick trên các mục bằng DataTemplate

<ListBox ItemsSource="{Binding Path=Templates}" 
     ItemTemplate="{StaticResource fileTemplate}"> 

tôi xác định một DataTemplate cho tôi Items, trong đó bao gồm StackPanel s và TextBlock s.

<DataTemplate x:Key="fileTemplate"> 
    <Border> 
     <StackPanel> 
       <TextBlock Text="{Binding Path=Filename}"/> 
       <TextBlock Text="{Binding Path=Description}"/> 
     </StackPanel> 
    </Border> 
</DataTemplate> 

Bây giờ tôi muốn phát hiện sự kiện nhấp đúp cho mục danh sách được nhấp đúp. Hiện tại tôi đã thử làm theo, nhưng nó không hoạt động vì nó không trả lại Item bị ràng buộc với số ListBox nhưng là TextBlock.

if (TemplateList.SelectedIndex != -1 && e.OriginalSource is Template) 
{ 
    this.SelectedTemplate = e.OriginalSource as Template; 
    this.Close(); 
} 

một cách sạch để xử lý một-click-event đúp vào một item trong một ListBox là gì, nếu các biểu tượng không ListBoxItems, nhưng riêng DataTemplates?

Trả lời

12

Tôi đã chơi xung quanh với điều này và tôi nghĩ rằng tôi đã đến đó ...

Tin tốt là, mà bạn có thể áp dụng một kiểu để ListBoxItem bạn áp dụng một DataTemplate - một trong những không loại trừ người kia ...

Nói cách khác, bạn có thể có một cái gì đó như sau:

<Window.Resources> 
     <DataTemplate x:Key="fileTemplate" DataType="{x:Type local:FileTemplate}"> 
... 
     </DataTemplate> 
    </Window.Resources> 

    <Grid> 

     <ListBox ItemsSource="{Binding Templates}" 
       ItemTemplate="{StaticResource fileTemplate}"> 
      <ListBox.ItemContainerStyle> 
       <Style TargetType="{x:Type ListBoxItem}"> 
        <EventSetter Event="MouseDoubleClick" Handler="DoubleClickHandler" /> 
       </Style> 
      </ListBox.ItemContainerStyle> 
     </ListBox> 

    </Grid> 

và sau đó thực hiện một handler trong Window của bạn, giống như

public void DoubleClickHandler(object sender, MouseEventArgs e) 
{ 
    // item will be your dbl-clicked ListBoxItem 
    var item = sender as ListBoxItem; 

    // Handle the double-click - you can delegate this off to a 
    // Controller or ViewModel if you want to retain some separation 
    // of concerns... 
} 
Các vấn đề liên quan