【问题标题】:Getting the row on the button_click event inside a DataGrid column in WPF在 WPF 中的 DataGrid 列中获取 button_click 事件的行
【发布时间】:2019-08-10 13:16:43
【问题描述】:

我想恢复这个thread。我有同样的情况,但任何解决方案都对我有用。 我有以下 xml,你可以看到类似的问题:

  <DataGrid Grid.Column="1" Name="Info_DG" FontSize="18" CellEditEnding="Info_DG_CellEditEnding" >
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding BM}"/>
                <DataGridTextColumn Binding="{Binding BC}"/>
                <DataGridTemplateColumn>                        
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Click="Button_Click"></Button>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>

我的目标与thread 相同:获取按下按钮的行号,但列出的任何解决方案都适用于我。

以下两种解决方案均无效,在我的情况下,DataContext 和 ID 均为空:

MyObject obj = ((FrameworkElement)sender).DataContext as MyObject;


object ID = ((Button)sender).CommandParameter;

其他答案也以 DataContext 为基础,因此无法正常工作,因为它为空。我的代码有什么问题吗,因为它给了我一个空数据上下文?

【问题讨论】:

  • DataContextButton 应该是该行的集合项。尝试使用来自 vs 的 live tree explorer 检查 DataContext 是什么
  • 为什么需要行(或行索引)?
  • 修改该行中的一些数据(与用户无关)
  • 显然,行的 DataContext 不是 MyObject 类型。列表项的类型是什么?
  • @UncoProg:您如何设置Info_DGItemsSource 属性以及设置什么?您试图在事件处理程序中获得什么值?

标签: c# xml wpf


【解决方案1】:

我认为您缺少 ItemSource?

<DataGrid ItemSource="{Binding YourItemSource}" Grid.Column="1" Name="Info_DG" FontSize="18" CellEditEnding="Info_DG_CellEditEnding" >
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding BM}"/>
            <DataGridTextColumn Binding="{Binding BC}"/>
            <DataGridTemplateColumn>                        
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Button Click="Button_Click"></Button>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>

对于您的数据上下文问题,最好先了解什么是数据上下文,请阅读以下链接。下面的帖子以最简单的方式解释了如何分配数据上下文,这是第 1 步。但是,您应该始终将数据上下文链接到视图模型(第 2 步)。

https://www.wpf-tutorial.com/data-binding/using-the-datacontext/

【讨论】:

    猜你喜欢
    • 2011-01-15
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 2010-11-20
    • 2017-07-23
    • 1970-01-01
    • 2016-03-31
    • 2011-04-24
    相关资源
    最近更新 更多