按钮单击事件上的未处理异常

本文关键字:未处理 异常 单击 事件 按钮 | 更新日期: 2023-09-27 18:03:16

我已经将一个数据表(在运行时填充)绑定到我的数据网格,并且有一个列列出文件路径。我对该列进行了定制,用图像按钮替换文件路径,以便在单击时打开文件。我得到以下错误,但还没有能够解决。任何方向将非常感激!

错误:类型为"Microsoft.CSharp.RuntimeBinder"的未处理异常。在System.Core.dll中发生了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:

<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";
    }
}

按钮单击事件上的未处理异常

为什么要从按钮的DataContext中获得未定义的Master ?为什么会出现错误

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

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

谢谢你们,你们给我指明了正确的方向。我认为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);
        }

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