[英]Can't set ItemsSource property without TargetInvocationException
I'm trying to show paths of files in a directory in DataGrid. 我正在尝试显示DataGrid目录中文件的路径。 To do this, for the past hour I've been trying to set ItemsSource property of a dataGrid, but whatever I do I keep getting TargetInvocationException.
为此,在过去的一个小时中,我一直在尝试设置dataGrid的ItemsSource属性,但是无论如何我都会不断收到TargetInvocationException。 I tried to use differents types of collections, even tried using Listbox or ListView, but no use.
我试图使用不同类型的集合,甚至尝试使用Listbox或ListView,但没有用。 I'm using Visual Studio 2015 Community RC.
我正在使用Visual Studio 2015社区RC。 This is the error I'm getting:
这是我得到的错误:
An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll PresentationFramework.dll中发生了类型为'System.Reflection.TargetInvocationException'的未处理异常
Additional information: Exception has been thrown by the target of an invocation. 附加信息:调用的目标已引发异常。
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 Code: WPF代码:
<DataGrid x:Name="grid" Margin="5,30,5,5">
</DataGrid>
The event is probably raised before the elements are fully loaded or the references are still unset, hence the exceptions. 该事件可能是在元素完全加载之前或未设置引用之前引发的,因此是异常。
private void textBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (!grid.IsLoaded)
return;
//rest of your code
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.