![](/img/trans.png)
[英]Why can't I use “HasItems” property on ContextMenu with ItemsSource?
[英]Can't set ItemsSource property without TargetInvocationException
我正在尝试显示DataGrid目录中文件的路径。 为此,在过去的一个小时中,我一直在尝试设置dataGrid的ItemsSource属性,但是无论如何我都会不断收到TargetInvocationException。 我试图使用不同类型的集合,甚至尝试使用Listbox或ListView,但没有用。 我正在使用Visual Studio 2015社区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>
该事件可能是在元素完全加载之前或未设置引用之前引发的,因此是异常。
private void textBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (!grid.IsLoaded)
return;
//rest of your code
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.