从ListView命令绑定中传递的CommandParameter为null。

3
我无法成功从ListView项发送CommandParameter。 我的代码如下。
<ListView x:Name="myList" ItemsSource="{Binding MyData}"                        
     <ListView.View>
          <GridView>
               <GridViewColumn>
                    <GridViewColumn.CellTemplate>
                          <DataTemplate>
                                <Button Command="{Binding Path=DataContext.MyCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}" CommandParameter="{Binding SelectedItem, ElementName=myList}" >
                                      <Button.Content>
                                            <StackPanel Orientation="Horizontal">
                                                <TextBlock Text="{Binding Path=SomeValue}" />
                                            </StackPanel>      
                                      </Button.Content>
                                 </Button>
                           </DataTemplate>   
                      </GridViewColumn.CellTemplate>
               </GridViewColumn>
          </GridView>
     </ListView.View>
</ListView>

当 ListView 上的项目被单击时,命令会被调用,但 CommandParameter 显示为 Nothing。 这里出了什么问题?

ViewModel 命令在这里:

Public ReadOnly Property MyData As List(Of myObject)
    Get
        Return _myObjectrepo.GetAll()
    End Get 
End Property

Public Property MyCommand As ICommand
    Get
        If _myCommand Is Nothing Then
            _myCommand = New RelayCommandWithParameter(Of myObject)(AddressOf Navigate)
        End If
        Return _myCommand 
    End Get
    Set(value As ICommand)
        _myCommand = value
    End Set
End Property
Private _myCommand As ICommand

...以及我尝试使用CommandParameter的步骤。

Private Sub Navigate(m As myObject)
    If m IsNot Nothing Then

    End If
End Sub

...但是上述过程中的m为空。


1
{Binding Path=SelectedItem, ElementName=myList} 应该可以解决问题。 - Omri Btian
你能发布一下命令代码吗?可能是类型转换有问题。 - Miran
假设MyData是一个X的集合,请确保您的viewModel中的命令定义将X作为参数传入。 - Omri Btian
在 Visual Studio 的输出窗口中是否有任何绑定错误? - Sheridan
2
尝试使用CommandParameter="{Binding}"来为所点击的项目绑定。 - ZSH
显示剩余4条评论
1个回答

9

我从评论中复制了答案:

CommandParameter="{Binding}" 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接