如何在wpf数据网格中获取控件

时间:2013-01-28 06:46:43

标签: wpf silverlight wpfdatagrid

我有一个包含多行的数据网格。在每一行内,第一列是一个按钮。我有行索引。假设我的行索引是7.现在我想获取第7行内的按钮并更改其内容。

如何在数据网格的特定行内获得此按钮控件并更改其值?

1 个答案:

答案 0 :(得分:0)

或许,以下代码可以解决您的问题。

<DataGridTemplateColumn>
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Click="ShowHideDetails">Details</Button>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
  </DataGridTemplateColumn>

在Codebehind C#中访问控件

private void ShowHideDetails(object sender, RoutedEventArgs e)
        {
            // You can access the button and do whateve the changes you want
            Button objMyButton = null;
            if (sender is Button)
            {
                objMyButton = (sender as Button);

            }

            //You can access the parent object which means corresponding DataGridRow and do whatever you want

            for (var vis = sender as Visual; vis != null; vis = VisualTreeHelper.GetParent(vis) as Visual)
                if (vis is DataGridRow)
                {
                    var row = (DataGridRow)vis;                 
                    break;
                }
        }