【问题标题】:DataGrid CellTemplate, Pass DataContext as Command ParameterDataGrid CellTemplate,将 DataContext 作为命令参数传递
【发布时间】:2017-05-31 13:20:17
【问题描述】:

我有一个DataGrid,其中ItemsSource 设置为ObservableCollection<ObservablePuls>

在最后一列我有一个按钮,我想将它的CommandParameter 绑定到ObservablePuls。使用此代码,我将 null 作为 CommandParameter 传递,并且此错误:

BindingExpression 路径错误:“DataContext”属性未在 '对象' ''ObservablePuls' (HashCode=40133923)'。 绑定表达式:路径=数据上下文; DataItem='ObservablePuls' (哈希码=40133923);目标元素是 'Button' (Name='');目标 属性是'CommandParameter'(类型'Object')

所以这是我的问题:如何传递作为行源的对象?

这是DataGrid的代码,带有按钮(省略其他列):

<DataGrid x:Name="PulsesDataGrid"
          Grid.Row="1"
          ItemsSource="{Binding ObservableUser.Pulses}"
          CanUserAddRows="False"
          CanUserSortColumns="True"
          AutoGenerateColumns="False"
          materialDesign:DataGridAssist.CellPadding="13 8 8 8"
          materialDesign:DataGridAssist.ColumnHeaderPadding="8"
          CanUserDeleteRows="False"
          CanUserReorderColumns="True"
          HorizontalAlignment="Stretch">
    <DataGrid.Columns>

        //... Other columns here

        <DataGridTemplateColumn Header="">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button Style="{StaticResource MaterialDesignToolButton}"
                            Margin="10 0 0 0"
                            Command="{Binding ElementName=PulsesDataGrid, Path=DataContext.DeleteRowInDataGrid}"
                            CommandParameter="{Binding Path=DataContext}">
                        <materialDesign:PackIcon Kind="DeleteForever" />
                    </Button>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

绑定Command 很好,因为它是使用空参数调用的;(

【问题讨论】:

    标签: c# wpf datagrid


    【解决方案1】:

    您可以使用以下方法将 DataTemplate 中的当前 DataContext(即行中显示的元素)绑定到 CommandParameter:

    CommandParameter="{Binding}"
    

    【讨论】:

    • 就是这么简单:|我在上面坐了 2 小时……无论如何谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-03-25
    • 2011-09-06
    • 2013-07-15
    • 2015-04-11
    • 2016-02-07
    • 2016-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多