我想知道 ListBox
是否有双击功能可以很容易地建立。我有一个 ListBox
集合为 ItemSource
.该集合包含自己的数据类型。
<ListBox ItemsSource="{Binding Path=Templates}"
ItemTemplate="{StaticResource fileTemplate}">
我定义了一个 DataTemplate
对于我的 Items
, 其中包括 StackPanel
s 和 TextBlock
<DataTemplate x:Key="fileTemplate">
<Border>
<StackPanel>
<TextBlock Text="{Binding Path=Filename}"/>
<TextBlock Text="{Binding Path=Description}"/>
</StackPanel>
</Border>
</DataTemplate>
现在我想检测双击列表项的双击事件。目前我尝试使用以下方法,但它不起作用,因为它不返回绑定(bind)到 ListBox
的项目但是 TextBlock
.
if (TemplateList.SelectedIndex != -1 && e.OriginalSource is Template)
{
this.SelectedTemplate = e.OriginalSource as Template;
this.Close();
}
在 item
上处理双击事件的干净方法是什么?在ListBox
, 如果图标不是 ListBoxItems
, 但拥有 DataTemplates
?
最佳答案
我一直在研究这个,我想我已经做到了......
好消息是,您可以将样式应用到 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...
}
关于c# - 使用 DataTemplate 双击项目的列表框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1879244/