简体   繁体   中英

Update listbox in C# WPF

I currently have a C# application for the purpose of testing specific parameters on a device. I have created the application with a separate class for dealing with tests. I would like to have the list box update automatically after every item is added to it from the "Test Class".

The "MainWindow" class I have for the UI creates a new "Test" class on button click..

public partial class MainWindow : Window{


    //Other initializing steps..

        private void BeginTestButton_Click(..){
            TestClass tc = new TestClass(this); //<-- passing this class in
            tc.testAll();
        } 
}

where the testAll function inside the "TestClass" looks something like this..

    public void testAll(){
        view.getListBox().add(test1()); 
        view.getListBox().add(test2());
        view.getListBox().add(test3());
        // and so on
    }

Where view is the UI class and the getListBox() is the listbox in question. Each "test" performed returns some string which would be the result of the test.

What methods are available to me for having these test results added to a list box and update after each test is finished? Thanks!

You'll want to do something with the TestClass, likely have it extend INotifyPropertyChanged. From there you can add a property on the TestClass. Adjust your listbox to show more than just a string/tag, if you haven't, like this:

<ListBox x:Name="ListBox">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Label Content="{Binding TestName}"></Label>
                <Label Content="{Binding TestCompleteStatus}"></Label>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Then, Whenever you kick off your test, you'll need to change your TestCompleteStatus property in the TestClass (make sure to do this on the UI thread or with dispatcher, as you'll be bound to the UI now). After your property has changed the ListBox will automatically update with the new property value. This is the functionality of INotifyPropertyChanged.

public void testAll(){
    view.getListBox().add(test1()); 
    view.getListBox().add(test2());
    view.getListBox().add(test3());
    // and so on
  }

You Need To change test1() from void to any func ex:

  int test1(){

 // now retern value
  return 0;
 }

    public void testAll(){
    view.getListBox().add(Convert.ToInt32(test1())); 

    }

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