【发布时间】:2015-11-12 20:08:26
【问题描述】:
我找不到针对此问题的简单解决方案。这就是我问的原因。
我有一个像这样的 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 属性成功改变了自身。但我想做的是更改 another 类 或 线程中的属性。我尝试的是这样的:
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.");
}
}
【问题讨论】:
-
通常您需要将 ui 更改从另一个线程分派到主线程。就像那里描述的那样:stackoverflow.com/a/14890338
标签: c# wpf multithreading user-interface