2009-12-10 70 views
5

我想知道是否可以輕鬆構建ListBox的雙擊功能。我有一個ListBox與集合ItemSource。該集合包含自己的數據類型。列表框DoubleClick使用DataTemplate的項目

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

我爲我的Items,它由StackPanel S和TextBlock已定義一個DataTemplate

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

現在我想檢測雙擊列表項的雙擊事件。目前我嘗試了以下操作,但它不起作用,因爲它不會返回綁定到ListBox但是TextBlock的項。

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

什麼是清潔的方式在ListBox處理上item雙擊事件,如果該圖標是不是ListBoxItems,但自己DataTemplates

回答

12

我一直在玩這個周圍,我想我已經到了那裏......

好消息是,你可以將樣式應用於您的ListBoxItem的申請一個DataTemplate - 一個不排除其他...

換句話說,你可以像下面這樣:

<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> 

,然後在窗口中執行的處理程序,像

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... 
}