![](/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.