E
E
Evgeny Ivanov2021-06-25 11:55:27
WPF
Evgeny Ivanov, 2021-06-25 11:55:27

How to add rows from a stream to a listbox?

XAML WPF project.
Most likely I'm doing many things wrong, please correct me.

I am writing an application to search for exe files in a folder.
The essence is simple - we found an exe file in the folder - we put the path to it in the listbox.

In XAML markup, I have a listbox And I need to add lines (elements) there. MainWindow.xaml.cs
<ListBox Name="ListBox1" Grid.Row="0"/>


public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
    
// Поиск в потоке
Thread thread1 = new Thread(InstalledPrograms.FindPrograms);
thread1.Start(); // Запуск потока.
}
}

static class InstalledPrograms
{
public static void FindPrograms()
{
// Тут позже будет код поиска программ.

//Ошибка - Для нестатического поля, метода или свойства "MainWindow.ListBox1" требуется ссылка на объект.
MainWindow.ListBox1.Items.Add("Путь к программе");
}
}


1) How to add lines from a stream to a listbox?
PS
What is the difference between MainWindow.xaml.cs and App.xaml.cs? Maybe I'm not writing the code there yet?
Yes, there is signed MainWindow.xaml.cs - Interaction logic for MainWindow.xaml and
App.xaml.cs - Interaction logic for App.xaml, but where to write the code?
More precisely, on what basis (and whether it is necessary) to separate it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vasily Bannikov, 2021-06-25
@vabka

What is the difference between MainWindow.xaml.cs and App.xaml.cs? Maybe I'm not writing the code there yet?

MainWindow is about the main window. App is about the application as a whole.
How to add rows from a stream to a listbox?

You cannot add from another thread, since UI elements can only be accessed from the UI thread.
The non-static field, method, or property "MainWindow.ListBox1" requires an object reference.

Well, yes, you can't. You need to pass an instance of the window.
For example like this:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
    
// Поиск в потоке
Thread thread1 = new Thread(()=>InstalledPrograms.FindPrograms(this));
thread1.Start(); // Запуск потока.
}
}

static class InstalledPrograms
{
public static void FindPrograms(MainWindow mainWindow)
{
// Тут позже будет код поиска программ.

//Ошибка - Для нестатического поля, метода или свойства "MainWindow.ListBox1" требуется ссылка на объект.
mainWindow.ListBox1.Items.Add("Путь к программе");
}
}

A
Alexander Ananiev, 2021-06-25
@SaNNy32

Use events. In the class that is looking for the file, define an event that the file is found. Subscribe to this event in the window class and add the path to the listbox in the handler.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question