【问题标题】:Update listbox in C# WPF在 C# WPF 中更新列表框
【发布时间】:2018-07-08 15:53:14
【问题描述】:

我目前有一个 C# 应用程序,用于测试设备上的特定参数。我用一个单独的类创建了应用程序来处理测试。我希望在从“测试类”中添加每个项目后自动更新列表框。

我为 UI 使用的“MainWindow”类在按钮单击时创建了一个新的“Test”类..

public partial class MainWindow : Window{


    //Other initializing steps..

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

“TestClass”中的 testAll 函数看起来像这样......

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

其中 view 是 UI 类,getListBox()是有问题的列表框。执行的每个“测试”都会返回一些作为测试结果的字符串。

我可以使用哪些方法将这些测试结果添加到列表框中并在每次测试完成后更新?谢谢!

【问题讨论】:

    标签: c# wpf listbox


    【解决方案1】:

    您将希望对 TestClass 做一些事情,可能让它扩展 INotifyPropertyChanged。从那里您可以在 TestClass 上添加一个属性。调整您的列表框以显示的不仅仅是字符串/标签,如果您还没有,如下所示:

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

    然后,无论何时开始测试,您都需要更改 TestClass 中的 TestCompleteStatus 属性(确保在 UI 线程或使用调度程序执行此操作,因为您现在将绑定到 UI)。在您的属性更改后,ListBox 将使用新的属性值自动更新。这是 INotifyPropertyChanged 的​​功能。

    【讨论】:

    • 感谢您的回答!只是为了澄清,我只需要确保 UI 线程看到每个测试的 CompleteStatus 的值?
    • 如果您的测试在单独的线程上执行,您只需要确保它们在 UI 线程上更新 CompleteStatus。如果您没有使用其他线程来运行这些测试,那么您无需担心。如果你是,它就像做 App.Current.Dispatcher.Invoke(new Action(delegate{ Test1.CompleteStatus = "result"; }));调度程序始终在 UI 线程上运行,并确保您不会遇到跨线程问题。
    【解决方案2】:
    public void testAll(){
        view.getListBox().add(test1()); 
        view.getListBox().add(test2());
        view.getListBox().add(test3());
        // and so on
      }
    

    您需要将 test1() 从 void 更改为任何 func ex:

      int test1(){
    
     // now retern value
      return 0;
     }
    
        public void testAll(){
        view.getListBox().add(Convert.ToInt32(test1())); 
    
        }
    

    【讨论】:

      猜你喜欢
      • 2011-02-28
      • 1970-01-01
      • 1970-01-01
      • 2014-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多