【发布时间】:2016-06-27 15:48:21
【问题描述】:
我已经看到了几个与我类似的问题,所以请不要很快忽略它。这里的情况似乎不同,我不明白为什么会出错。我的DataGrid 与键和鼠标点击有一些绑定:
<DataGrid x:Name="gridStudents" ItemsSource="{Binding Source={StaticResource cvsStudentList}}"
Margin="2"
Height="250"
SelectedItem="{Binding SelectedStudentItem, UpdateSourceTrigger=PropertyChanged}"
AutoGenerateColumns="False" IsReadOnly="True" IsSynchronizedWithCurrentItem="True" SelectionChanged="gridStudents_SelectionChanged">
<DataGrid.InputBindings>
<MouseBinding
MouseAction="LeftDoubleClick"
Command="{Binding EditStudentButtonClickCommand}"
CommandParameter="{Binding /}" />
<KeyBinding Key="Delete" Command="{Binding DeleteStudentButtonClickCommand}" />
</DataGrid.InputBindings>
感谢 StackOverflow 和现有用户的贡献,我找到了这种方法。非常感谢。
此问题与MouseBinding CommandParameter 有关。该程序执行良好,没有任何警告。我可以双击DataGrid 中的任何一行,它的行为与设计相同。
但如果我检查 Visual Studio 2015 中的 Output 窗口,我可以看到以下备注:
System.Windows.Data 错误:40:BindingExpression 路径错误:在“当前集合项”“OCLMEditorModelView”(HashCode=43686667)上找不到“属性”。绑定表达式:路径=/; DataItem='OCLMEditorModelView' (HashCode=43686667);目标元素是“MouseBinding”(HashCode=49684624);目标属性是'CommandParameter'(类型'Object')
为什么这么说?我使用了/,因为ItemSource 是一个CollectionViewSource 对象,我知道/ 调用了当前选定的项目。但是,在我实际双击一行之前,该命令不应该触发。
很好奇如何阻止它出现在我的输出窗口中。
如果我尝试根据答案更改绑定,则会收到此异常:
更新:
这是当前的 XAML:
<MouseBinding
MouseAction="LeftDoubleClick"
Command="{Binding EditStudentButtonClickCommand}"
CommandParameter="{Binding /, Source={RelativeSource Self}}" />
但现在我在输出窗口中注意到了这一点:
System.Windows.Data 错误:40:BindingExpression 路径错误:'' 在“当前收藏项”“RelativeSource”上找不到属性 (哈希码=472027)'。绑定表达式:路径=/; DataItem='RelativeSource' (HashCode=472027);目标元素是 '鼠标绑定' (HashCode=36454430);目标属性是 'CommandParameter'(类型'对象')
它似乎工作(我可以双击一行,它会做我想要的)。那么我可以停止这个输出警告吗?
更新:
这就是当前的 XAML:
<DataGrid x:Name="gridStudents" ItemsSource="{Binding StudentsView}"
Margin="2"
Height="250"
SelectedItem="{Binding SelectedStudentItem, UpdateSourceTrigger=PropertyChanged}"
AutoGenerateColumns="False" IsReadOnly="True" IsSynchronizedWithCurrentItem="True" SelectionChanged="gridStudents_SelectionChanged">
<DataGrid.InputBindings>
<MouseBinding
MouseAction="LeftDoubleClick"
Command="{Binding EditStudentButtonClickCommand}"
CommandParameter="{Binding /, Source={RelativeSource Self}}" />
<KeyBinding Key="Delete" Command="{Binding DeleteStudentButtonClickCommand}" />
</DataGrid.InputBindings>
<DataGrid.CellStyle>
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="VerticalContentAlignment" Value="Center"/>
</Style>
</DataGrid.CellStyle>
我尝试做的事情没有改变 - 当用户双击 DataGrid 行(绑定到 cvs)时,它会调用基于该行的命令。
【问题讨论】:
-
不要使用
Convert.ChangeType,只写(T)parameter。 -
RelativeSource扩展名仅对RelativeSource属性有效,对Source无效。另外RelativeSource Self会引用MouseBinding,这肯定不是你的收藏,你到底在做什么...... -
@H.B.更新的问题(底部)。
-
您的绑定仍然损坏,这不是一个问题,这是关于您似乎不知道如何构建有效绑定的声明。另外:如果您的命令在没有传递命令参数的情况下完成了它应该做的事情(因为绑定失败),那么首先停止传递参数。
-
@H.B.当然!网格已经绑定到当前项目。不需要参数。傻我。谢谢。
标签: c# wpf xaml binding commandparameter