Question

I have this code in VB.Net, in windows forms. I need to wait for the user's choice, but keeping the UI responsive, so the user can select a option from a ListBox. The listbox_SelectionChanged event will set a Boolean named selectedElement to true, so the execution continues. In WPF I have found that it is possible to do it with threading but I am not sure how to do it. Any advice? Thanks :)

    Do
       System.Windows.Forms.Application.DoEvents()
    Loop Until selectedElement
Was it helpful?

Solution

That is a terribly bad way to code. Even in winforms.

First of all, if you're working in WPF you really need to understand The WPF Mentality.

in MVVM WPF, your ViewModel should control the actions executed by the application upon reacting to user input.

Generally speaking, this is how you deal with "wait for the user to select an item in a ListBox in WPF:

XAML:

<ListBox ItemsSource="{Binding SomeCollection}"
         SelectedItem="{Binding SelectedItem}"/>

ViewModel:

public class SomeViewModel
{
    public ObservableCollection<SomeData> SomeCollection {get;set;}

    //Methods to instantiate and populate the Collection.

    private SomeData _selectedItem;
    public SomeData SelectedItem
    {
        get { return _selectedItem; }
        set
        {
            _selectedItem = value;
            //PropertyChanged() is probably desired here.

            UserHasSelectedAnItem(); //Method invocation
        }
    }

    private void UserHasSelectedAnItem()
    {
       //Actions after the user has selected an item
    }
}

Notice how this is fundamentally different from the RefreshTheUIHack(); loop approach.

There's no need to "loop" anything because WPF (and also winforms) already have an internal "message loop" which listens for user input and raises events when needed.

I suggest you read the above linked answer and related blog posts to understand what you need in order to move from the traditional, procedural winforms approach into the DataBinding-based WPF mentality.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top