【问题标题】:Can't set ItemsSource property without TargetInvocationException没有 TargetInvocationException 无法设置 ItemsSource 属性
【发布时间】:2015-10-28 23:54:08
【问题描述】:

我正在尝试在 DataGrid 的目录中显示文件的路径。为此,在过去的一个小时里,我一直在尝试设置 dataGrid 的 ItemsSource 属性,但无论我做什么,我都会收到 TargetInvocationException。我尝试使用不同类型的集合,甚至尝试使用 Listbox 或 ListView,但没有用。我正在使用 Visual Studio 2015 Community RC。这是我得到的错误:

PresentationFramework.dll 中出现“System.Reflection.TargetInvocationException”类型的未处理异常

附加信息:调用目标已引发异常。

public partial class MainWindow : Window
{
    List<FileInfo> fileInfo = new List<FileInfo>();

    public MainWindow()
    {
        InitializeComponent();
    }

    private void textBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        string path = textBox.Text;
        if (Directory.Exists(path))
        {
            string[] fileEntries = Directory.GetFiles(path);
            fileInfo.Clear();
            foreach (string s in fileEntries)
                fileInfo.Add(new FileInfo() { Path = s });
            grid.ItemsSource = fileInfo;
        }
    }
}

public class FileInfo
{
    public string Path { get; set; }
}

WPF 代码:

<DataGrid x:Name="grid" Margin="5,30,5,5">
    </DataGrid>

【问题讨论】:

    标签: c# wpf visual-studio datagrid invocationtargetexception


    【解决方案1】:

    该事件可能在元素完全加载或引用仍未设置之前引发,因此存在异常。

            private void textBox_TextChanged(object sender, TextChangedEventArgs e)
        {
                if (!grid.IsLoaded)
                return;
       //rest of your code
      }
    

    【讨论】:

    • 是的,该事件是在设置 textBox 文本时引发的,此时网格尚未加载。我修复了代码,现在它可以工作了。无法告诉你我有多开心:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多