2009-12-10 11 views
5

ListBoxのダブルクリック機能を簡単に構築できるかどうかを知りたいと思います。私にはというようなコレクションがあるListBoxがあります。コレクションには、独自のデータ型が含まれています。ListBoxでDataTemplateを使用するアイテムにDoubleClickを使用する

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

私はStackPanel sおよびTextBlock秒で構成され、私のItemsため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(); 
} 

アイコンはListBoxItemsが、自身のDataTemplatesされていない場合、ListBoxitemをダブルクリックイベントを処理するためのクリーンな方法は何ですか?

答えて

12

私はこれで遊んでてきたと私は私がそこに着いたと思う...

良いニュースは、あなたのListBoxItem にスタイルを適用することができること、であるとはDataTemplateを適用 - 1をその後、

<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... 
} 
関連する問題