gpt4 book ai didi

c# - 为什么 UI 元素不在 Button Click 事件处理程序中反射(reflect)它们的状态?

转载 作者:太空宇宙 更新时间:2023-11-03 19:35:37 25 4
gpt4 key购买 nike

在下面的例子中,我怎样才能得到:

  • 按钮为“禁用-灰色”
  • 消息说“正在工作......”

同时工作正在完成,而不是之后工作完成?

XAML:

<Window x:Class="TestIsEnabled8938.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel Margin="10" HorizontalAlignment="Left">

<Button x:Name="Button_Refresh"
HorizontalAlignment="Left"
DockPanel.Dock="Top"
Content="Refresh"
Click="Button_Refresh_Click"
Height="25"
Width="200"/>

<TextBlock x:Name="Message" Text="Button is ready to click."/>
</StackPanel>
</Window>

代码隐藏:

using System.Windows;
using System.Threading;

namespace TestIsEnabled8938
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}

private void Button_Refresh_Click(object sender, RoutedEventArgs e)
{
Message.Text = "working...";
Button_Refresh.IsEnabled = false;

//do work
Thread.Sleep(2000);

Message.Text = "Button is ready to click again.";
Button_Refresh.IsEnabled = true;
}
}
}

这也行不通:

Dispatcher.Invoke(new Action(() => { Message.Text = "working..."; }));
Dispatcher.Invoke(new Action(() => { Button_Refresh.IsEnabled = false; }));

回答:

感谢 Heinzi,这段代码有效:

using System.Windows;
using System.Threading;
using System.ComponentModel;

namespace TestIsEnabled8938
{
public partial class Window1 : Window
{
BackgroundWorker backgroundWorker;

public Window1()
{
InitializeComponent();

backgroundWorker = new BackgroundWorker();

backgroundWorker.DoWork += (sender, args) =>
{
Thread.Sleep(3000);
};

backgroundWorker.RunWorkerCompleted += (sender, args) =>
{
Message.Text = "button is ready to click again";
Button_Refresh.IsEnabled = true;
};
}

private void Button_Refresh_Click(object sender, RoutedEventArgs e)
{
Message.Text = "working...";
Button_Refresh.IsEnabled = false;
backgroundWorker.RunWorkerAsync();
}
}
}

最佳答案

如果您希望 UI 在任务运行时更新(并保持响应),您需要使用单独的线程,例如使用 BackgroundWorker

代码示例(未经测试):

BackgroundWorker bwButtonWorker;

public Window1() {
InitializeComponent();

bwButtonWorker = new BackgroundWorker();

bwButtonWorker.DoWork += (sender, args) => {
// do your lengthy stuff here -- this happens in a separate thread
Thread.Sleep(2000);
}

bwButtonWorker.RunWorkerCompleted += (sender, args) => {
// this happens in the UI thread, so you can modify your UI elements here
Message.Text = "Button is ready to click again.";
Button_Refresh.IsEnabled = true;
}
}

private void Button_Refresh_Click(object sender, RoutedEventArgs e)
{
Message.Text = "working...";
Button_Refresh.IsEnabled = false;
bwButtonWorker.RunWorkerAsync();
}

关于c# - 为什么 UI 元素不在 Button Click 事件处理程序中反射(reflect)它们的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1778772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com