c# - 使用 DataTemplate 双击项目的列表框

标签 c# wpf events event-handling listbox

我想知道 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/

相关文章:

c# - 处理泄漏的 IAsyncDisposable 实例的推荐方法是什么?

C# 和 MySql,在两个日期之间选择

windows - 有没有更有效的方法来设置 RadioButton 的 CheckChanged 事件的变量?

c# - 列表框项目删除

javascript - JQuery 3.4.1 无法读取未定义的属性 'value'

events - PostgreSQL 中的事件调度器?

c# - 在 C# 中使用正则表达式(正则表达式)从字符串中获取值

c# - 如何使用 Linq-2-Sql 将域逻辑与数据库/持久性逻辑分开?

c# - 如何从资源项目中获取图像

wpf - 如何停止Wpf Tabcontrol卸载选项卡更改上的可视树