按钮点击事件

时间:2016-08-20 05:10:23

标签: c# wpf xaml datagrid datatemplate

我已将数据表(在运行时填充)绑定到我的数据网格,并有一列列出文件路径。我正在自定义该列以使用图像按钮替换文件路径以在单击时打开文件。我收到以下错误,但无法解决。任何方向都将非常感谢!

错误: System.Core.dll中发生未处理的“Microsoft.CSharp.RuntimeBinder.RuntimeBinderException”类型异常 附加信息:'System.Data.DataRowView'不包含'Master'的定义

我的按钮事件出错...“d.Master”。

private void ButtonClick(object sender, RoutedEventArgs e)
{
    Button button2 = (Button)e.OriginalSource;
    dynamic d = button2.DataContext;
    string filepath = d.Master;
    Process.Start(filepath); 
}

数据网格:

<DataGrid x:Name="DataGrid1" HorizontalAlignment="Stretch" 
          Margin="650,197,449,0" VerticalAlignment="Stretch" 
          AutoGenerateColumns="True" AutoGeneratingColumn="DataGrid_AugoGeneratingColumn" ItemsSource="{Binding fileTable}">
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Master" CellTemplate="{StaticResource DataTemplate2}"/>
    </DataGrid.Columns>
</DataGrid>

的DataTemplate

<DataTemplate x:Key="DataTemplate2">
<Button Name="fileButton" Click="ButtonClick" Width="30" Height="30" BorderBrush="#FF707070" BorderThickness="1,1,0,1">
    <Button.Background>
        <ImageBrush ImageSource="C:\Images\PDFicon.png" Stretch="Uniform"/>
    </Button.Background>
</Button>
</DataTemplate>

AutoGeneratingColumn方法:

private void DataGrid_AugoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    if (e.Column.Header.ToString() == "Master")
    {
        DataGridTemplateColumn templateColumn = new DataGridTemplateColumn    //create new template column
        CellTemplate = (DataTemplate) Resources["DataTemplate2"]
        e.Column = templateColumn; // Replace the auto-generated column with the templateColumn.
    }
    else
    {
        e.Column.Header = "Expired";
    }
}

3 个答案:

答案 0 :(得分:0)

为什么要尝试从按钮的Master获取未定义的DataContext?即为什么错误即将来临。

由于fileTable是数据网格的来源,因此您需要在Master数据类型中包含项fileTable。由于尚未定义,因此将产生错误。

最佳解决方案是在ItemsSource的数据类中使用Master属性,并相应地填充属性,以便在按钮单击期间,您可以通过DataContext访问它,就像您现在的操作一样。

答案 1 :(得分:0)

谢谢大家,这使我指出了正确的方向。我以为DataContext指向我指向数据表的“主”列本身,它在运行时生成而不是真正的属性。我通过识别所选单元格来修复我的问题。

        private void ButtonClick(object sender, RoutedEventArgs e)
    {
        //Get column Index of selected cell & set as variable
        int colIndex = BoundPivotGrid.CurrentCell.Column.DisplayIndex;
       DataRowView drv = (DataRowView)BoundPivotGrid.SelectedItem;
        String valueOfItem = drv[colIndex].ToString();

        if (valueOfItem == "-")
        {
            MessageBox.Show("No file");
        }
        else
        {
            Process.Start(valueOfItem);
        }

答案 2 :(得分:-1)

问题是“string filepath = d.Master;”。 d的类型为DataRowView,它没有名为Master的属性。将dynamic更改为var,它将在编译时而不是运行时失败