C#WPF - 如何简单地从另一个类/线程

时间:2015-11-12 20:08:27

标签: c# wpf multithreading user-interface

我无法找到解决此问题的简单解决方案。这就是我问的原因。

我有一个像这样的WPF 窗口

<Window x:Class="WPF_Test.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Width="640" Height="480">

    <Button Name="xaml_button" Content="A Text."/>
</Window>

MainWindow

using System.Windows;
using System.Threading;

namespace WPF_Test
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            xaml_button.Content = "Text changed on start.";
        }
    }

    private void xaml_button_Click()
    {
        Threading.t1.Start();
        UIControl.ChangeButtonName("Updated from another CLASS.");
    }
}

按钮的Content属性已成功自行更改。但我想要做的是更改另一个线程中的属性。我试过的是:

class UIControl
{
    public static void ChangeButtonName(string text)
    {
        var window = new MainWindow();
        window.xaml_button.Content = text;
    }
}

显然无法正常工作,因为public MainWindow()会将Content属性更改回原来的属性,并带来一些问题。

我也希望在多线程时使用它。我的简单线程类看起来像这样:

class Threading
{
    public static Thread t1 = new Thread(t1_data);

    static void t1_data()
    {
        Thread.Sleep(2000);
        UIControl.ChangeButtonName("Updated from another THREAD.");
    }
}

1 个答案:

答案 0 :(得分:2)

为此,我建议声明一个静态变量,该变量包含您喜欢的UI控件,在本例中为Button。同时在开头添加using System.Windows.Controls;。所以你的代码应该是这样的:

using System.Threading;
using System.Windows;
using System.Windows.Controls;

namespace WPF_Test
{
    public partial class MainWindow : Window
    {
        public static Button xamlStaticButton;

        public MainWindow()
        {
            InitializeComponent();
            xamlStaticButton = xaml_button;
            xamlStaticButton.Content = "Text changed on start";
        }

        private void xaml_button_Click(object sender, RoutedEventArgs e)
        {
            Threading.t1.Start();
            UIControl.ChangeButtonName("Updated from another CLASS.");
        }
    }
}

我所做的就是为按钮设置占位符,然后在开始时分配

class UIControl : MainWindow
{
    public static void ChangeButtonName(string text)
    {
        App.Current.Dispatcher.Invoke(delegate {
            xamlStaticButton.Content = text;
        });
    }
}

现在我继承了<{1}}类到MainWindow类,以方便使用。为了使这项工作与多线程,我添加了UIControl。即使您在另一个帖子确保您的用户界面也会更新。