简体   繁体   中英

Can't set ItemsSource property without TargetInvocationException

I'm trying to show paths of files in a directory in 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. I tried to use differents types of collections, even tried using Listbox or ListView, but no use. I'm using Visual Studio 2015 Community RC. This is the error I'm getting:

An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM