c# - ListBox SelectedIndex 作为命令参数
问题描述
Command 参数如何绑定到 ListBox 中的选定索引?我的代码:
<ListBox>
<i:Interaction.Triggers>
<i:EventTrigger
EventName="MouseDoubleClick">
<i:InvokeCommandAction
Command="{
Binding Path=SelectPath,
Mode=OneTime,
RelativeSource={
RelativeSource Mode=FindAncestor,
AncestorType={x:Type UserControl}
}
}"
CommandParameter="ListBox.SelectedIndex" // how can this parameter be bind to SelectedIndex
/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ListBox>
编辑:
我做了什么并且它有效:创建了新的 dp 属性 SelectedListBoxIndex 将其与 SelectedIndex 绑定,然后将属性作为命令参数传递。但是有没有更好的方法呢?
<ListBox
SelectedIndex="{
Binding Path=SelectedListBoxIndex,
RelativeSource={
RelativeSource Mode=FindAncestor,
AncestorType={x:Type UserControl}
}}">
<i:Interaction.Triggers>
<i:EventTrigger
EventName="MouseDoubleClick">
<i:InvokeCommandAction
Command="{
Binding Path=SelectPath,
Mode=OneTime,
RelativeSource={
RelativeSource Mode=FindAncestor,
AncestorType={x:Type UserControl}
}
}"
CommandParameter="{
Binding Path=SelectedListBoxIndex,
RelativeSource={
RelativeSource Mode=FindAncestor,
AncestorType={x:Type UserControl}
}
}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</ListBox>
解决方案
一种方法可能是设置您的 ListBox x:Name,然后将 CommandParameter 绑定到其 SelectedIndex 属性,如下所示:
<ListBox x:Name="lb">
<i:Interaction.Triggers>
<i:EventTrigger
EventName="MouseDoubleClick">
<i:InvokeCommandAction
Command="{
Binding Path=SelectPath,
Mode=OneTime,
RelativeSource={
RelativeSource Mode=FindAncestor,
AncestorType={x:Type UserControl}
}
}"
CommandParameter="{Binding ElementName=lb, Path=SelectedIndex}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</ListBox>
推荐阅读
- python - 在散景python中禁用滚动条
- java - ORA-01722 执行 PreparedStatement 时出错
- c++ - 使用 Boost read_graphviz 编译 C++ 代码
- git - 如何根据 Azure DevOps 中的分支部署到不同的环境?
- postgresql - 创建postgresql数据库的备份找不到文件
- java - 使用环境变量运行 Gradle 任务
- javascript - 如何在 JS React 中使用两个函数导出默认值?
- ios - SwiftUI NavigationLink 导致推送发生,然后在完成后弹出,然后再次推送
- azure-devops - 如何在 ftp 中使用 AzureDevOps 发布 asp.net 网站
- node.js - XPath 语句不返回值,而是 true 或 false