mar*_*tin 5 c# wpf events listbox event-handling
我想知道是否ListBox
可以轻松构建一个双击功能.我有一个ListBox
收藏品ItemSource
.该集合包含自己的数据类型.
<ListBox ItemsSource="{Binding Path=Templates}"
ItemTemplate="{StaticResource fileTemplate}">
Run Code Online (Sandbox Code Playgroud)
我DataTemplate
为我定义了一个Items
由StackPanel
s和TextBlock
s 组成的.
<DataTemplate x:Key="fileTemplate">
<Border>
<StackPanel>
<TextBlock Text="{Binding Path=Filename}"/>
<TextBlock Text="{Binding Path=Description}"/>
</StackPanel>
</Border>
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)
现在我想检测双击列表项的双击事件.目前我尝试使用以下,但它不起作用,因为它不会返回绑定到ListBox
但是的项目TextBlock
.
if (TemplateList.SelectedIndex != -1 && e.OriginalSource is Template)
{
this.SelectedTemplate = e.OriginalSource as Template;
this.Close();
}
Run Code Online (Sandbox Code Playgroud)
什么是干净的方法来处理的双击事件item
中ListBox
,如果图标都没有ListBoxItems
,但自己DataTemplates
?
kiw*_*pom 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>
Run Code Online (Sandbox Code Playgroud)
然后在你的Window中实现一个处理程序,就像
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...
}
Run Code Online (Sandbox Code Playgroud)