gpt4 book ai didi

c# - 具有值数据绑定(bind)的 WPF ProgressBar

转载 作者:太空狗 更新时间:2023-10-29 21:23:19 25 4
gpt4 key购买 nike

我正在尝试对 WPF 中 ProgressBar 的值属性进行数据绑定(bind)。我设置了一个按钮来增加 ProgressBar 值的数据绑定(bind) int 属性。当我按下按钮时,它应该使 ProgressBar 的值从 1 增加到 100。但是......它似乎没有工作,我不确定我做错了什么。这是我的 XAML...

<Window x:Class="ProgressBarExample2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="250" Width="400" Background="WhiteSmoke">
<StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
<Button Name="goButton" Height="30" Width="50" Margin="0,10,0,50" Click="goButton_Click">GO!</Button>
<ProgressBar Name="progressBar" Width="300" Height="30" Value="{Binding Percent, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>

这是我背后的代码...

public partial class MainWindow : Window, INotifyPropertyChanged
{
#region INotifyPropertyChanged

public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChange(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}

#endregion

private int percent = 0;
public int Percent
{
get { return this.percent; }
set
{
this.percent = value;
NotifyPropertyChange("Percent");
}
}

public MainWindow()
{
InitializeComponent();
}


private void goButton_Click(object sender, RoutedEventArgs e)
{
for (Percent = 0; Percent <= 100; Percent++)
{
Thread.Sleep(50);
}
}
}

最佳答案

Thread.Sleep 正在阻塞 UI 线程并停止进度条的动画。

您可以使用以下命令暂停执行而不阻塞 UI 线程。将您的 Thread.Sleep(50) 调用替换为 Wait(50)

/// <summary>
/// Stop execution for a specific amount of time without blocking the UI
/// </summary>
/// <param name="interval">The time to wait in milliseconds</param>
public static void Wait(int interval)
{
ExecuteWait(() => Thread.Sleep(interval));
}

public static void ExecuteWait(Action action)
{
var waitFrame = new DispatcherFrame();

// Use callback to "pop" dispatcher frame
IAsyncResult op = action.BeginInvoke(dummy => waitFrame.Continue = false, null);

// this method will block here but window messages are pumped
Dispatcher.PushFrame(waitFrame);

// this method may throw if the action threw. caller's responsibility to handle.
action.EndInvoke(op);
}

关于c# - 具有值数据绑定(bind)的 WPF ProgressBar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14262220/

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