【问题标题】:Attach new Timer to every Object将新计时器附加到每个对象
【发布时间】:2016-02-12 07:50:35
【问题描述】:

我正在使用 WPF 并创建了一个Window,其中包含有关计算机的信息。 它存储网络连接、IP、子网掩码、网络设备等信息。

为了跟踪系统中的变化,我想在对象上添加一个计时器来刷新自身。我不想刷新孔表格,因为我有HttpWebRequests,它会冻结程序几秒钟。应该更容易看到更改并突出显示它们。

例如:

StComputerInf.Children.Add(new Label { Content = "2. Domain: \t\t" + System.Environment.UserDomainName });

我想在这里添加一个计时器来刷新自己。

对于TreeView 中的每个TreeViewItem

public TreeView CreatTVConnection()
    {
        List<CAdapter> LAdapter = new List<CAdapter>();
        List<TreeViewItem> lConnectedDevices = new List<TreeViewItem>();
        List<TreeViewItem> lDisconnectedDevices = new List<TreeViewItem>();
        LAdapter = ReadAdapter();
        TreeView tv_Adapter = new TreeView();
        tv_Adapter.Name = "Adapter";
        tv_Adapter.Background = System.Windows.Media.Brushes.Transparent;
        tv_Adapter.BorderThickness = new Thickness(0);
        TreeViewItem Connected = new TreeViewItem();
        TreeViewItem Disconnected = new TreeViewItem();
        lConnectedDevices = LoadTV(true, LAdapter);
        if (lConnectedDevices.Count > 0)
        {
            Connected.Header = "Connected:";
            Connected.FontWeight = FontWeights.Bold;
            Connected.Foreground = System.Windows.Media.Brushes.Green;
            Connected.Name = "Connected";

            foreach (TreeViewItem tvi in lConnectedDevices)
            {
                tvi.FontWeight = FontWeights.Normal;
                Connected.Items.Add(tvi);
            }
        }
        ....

有没有办法查看一个对象是否发生了变化?所以我可以突出显示受影响的对象?

【问题讨论】:

    标签: c# wpf timer refresh


    【解决方案1】:

    使用工厂来创建您的对象。 因此,对于标签示例,您将使用类似 LabelFactory.Create(any useful parameters here) 作为该方法的一部分,您可以包含计时器等。

    另外,考虑使用 async/await 来更新您的表单,这是一种在不冻结表单的情况下更轻松地更新它们的方法。一旦您对这种模式感到满意,您应该能够消除对计时器的依赖。

    【讨论】:

    • 现在我尝试使用等待异步。但是,如果我运行 Task.Run(() =&gt;{} 并且我想在其中生成一个新标签,它会因“需要 STA 线程”而崩溃。看来他无法处理Window.Form 项目。
    • 对 UI 的任何更新都需要在 UI 线程上完成。查看 control.Invoke 了解如何操作
    猜你喜欢
    • 2022-01-18
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 2014-01-13
    • 2018-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多