GridViewRow在DataGrid中为null

时间:2013-02-08 06:46:26

标签: c# .net wpf datagrid

我是WPF的新手。我在我的wpf项目中将数据表绑定到数据网格。我的DataGrid和按钮点击事件中有按钮,我试图找到GridViewRow。但是我把Grdrow1称为null。

我的代码:

<my:DataGrid Name="GridView1" ItemsSource="{Binding}" AutoGenerateColumns="False" >
    <my:DataGrid.Columns>
        <my:DataGridTemplateColumn Header="Vehicle Reg. No." Width="SizeToCells">
            <my:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button Name="btnUserId" Cursor="Hand"  Click="btnUserId_Click" Content="{Binding Path=VehicleReg }" Style="{StaticResource LinkButton}"></Button>
                </DataTemplate>
            </my:DataGridTemplateColumn.CellTemplate>
        </my:DataGridTemplateColumn>
        <my:DataGridTextColumn Header="Vehicle Name"  Binding="{Binding Path=VehicleName}">
        </my:DataGridTextColumn>
    </my:DataGrid.Columns>
</my:DataGrid>

我的C#代码是:

private void btnUserId_Click(object sender, RoutedEventArgs e)
{            
    GridViewRow Grdrow1 = ((FrameworkElement)sender).DataContext as GridViewRow;
}

-------我编辑的帖子------

我在GridViewRow中使用了以下命名空间: -

使用System.Web.UI.WebControls;

这是我当前还是其他任何我必须使用的?

2 个答案:

答案 0 :(得分:0)

在代码隐藏构造函数中:

    public Window1()
    {
        InitializeComponent();
        var dt = new DataTable();
        dt.Columns.Add("col1");
        dt.Columns.Add("col2");
        dt.Rows.Add("11", "12");
        dt.Rows.Add("21", "22");
        this.GridView1.DataContext = dt;
    }

btnUser_Click

    private void btnUserId_Click(object sender, RoutedEventArgs e)
    {
        var Grdrow1 = ((FrameworkElement)sender).DataContext as DataRowView;
    }

你有一行

答案 1 :(得分:0)

首先,请确保您不会将DataGrid与GridView(ListView)混淆。看来您的Xaml正在使用DataGrid,但您正在尝试强制转换为DataGrids中不存在的GridViewRow。您可能正在寻找DataGridRow。

然而,进行此更改还不够 - 您仍然会尝试不会成功的演员表。 WPF中Click事件的发送者只是用于连接事件处理程序的对象,在这种情况下是Button。为了找到包含此Button的DataGridRow,您必须向上走WPF Visual Tree,直到使用VisualTreeHelper类找到它。

保持相同的Xaml,这是我为Click事件处理程序提出的建议。请注意,发件人是Button。从那开始,我们只使用VisualTree.GetParent方法爬上Visual Tree,直到找到第一个DataGridRow类型的对象。

private void btnUserId_Click(object sender, RoutedEventArgs e)
{            
    Button button = sender as Button;
    if (button == null)
        return;

    DataGridRow clickedRow = null;
    DependencyObject current = VisualTreeHelper.GetParent(button);

    while (clickedRow == null)
    {
        clickedRow = current as DataGridRow;
        current = VisualTreeHelper.GetParent(current);
    }

    // after the while-loop, clickedRow should be set to what you want
}