Pak
Pak

Reputation: 3

Can't clear ListBox while item is selected

Hello today I was experimenting with WPF and I found that when a ListBox has a selected item it will not allow it to be modified and hang the app

        private void Button_Click_7(object sender, RoutedEventArgs e)
    {
        ScriptBox.Items.Clear();
        Functions.PopulateListBox(ScriptBox, "./Scripts", "*.txt");
        Functions.PopulateListBox(ScriptBox, "./Scripts", "*.lua");
    }

I'm new to WPF so it would help a lot to find out why this happens.

Edit:Might Be Mscorelib.dll (Its Not)

Edit: A Try Catch Worked WITH Peregrine's Improvements

Upvotes: 0

Views: 186

Answers (2)

Peregrine
Peregrine

Reputation: 4556

Even if you're not going to go the full MVVM route, it's still a good idea to separate your application's data from the UI controls.

1] In the constructor of your Window, create an ObservableCollection<string> and set this as the ItemsSource of the ScriptBox control.

private ObservableCollection<string> _scriptBoxCollection;

public MyView()
{
    _scriptBoxCollection = new ObservableCollection<string>();
    ScriptBox.ItemsSource = _scriptBoxCollection ;
}       

2] Change your PopulateListBox() method to just return a collection of file names. Following the Single Responsibility Principle, such methods shouldn't care how the data they generate is used.

public ReadOnlyCollection<string> GetMatchingFiles(string folder, string fileSpec) { ... }

The return value is ReadOnlyCollection<T> in line with the Microsoft guidelines.

3] Change the button click handler so that it updates the observable collection.

private void Button_Click_7(object sender, RoutedEventArgs e)
{
    _scriptBoxCollectionClear();

    foreach(var item in Functions.GetMatchingFiles("./Scripts", "*.txt")
        _scriptBoxCollection.Add(item);

    Functions.GetMatchingFiles("./Scripts", "*.lua")
        _scriptBoxCollection.Add(item);
}

The ForEach construct is required as the standard ObservableCollection doesn't support AddRange().


Add this to Functions.cs (and depricate PopulateListBox() and any other similar methods that are writing data directly to UI controls)

public static ReadOnlyCollection<string> GetMatchingFiles(string folder, string fileType) 
{
    var result = new List<string>();
    var dinfo = new DirectoryInfo(folder); 
    var files = dinfo.GetFiles(fileType); 
    foreach (var file in files) 
    { 
        result.Add(file.Name); 
    } 
    
    return result.AsReadOnly();
}

Upvotes: 1

Aleks
Aleks

Reputation: 1

Have you tried using ScriptBox.UnselectAll() or ScriptBox.SelectedIndex = -1 ?

Assuming ScriptBox is your Listbox.

Upvotes: 0

Related Questions