带有值数据绑定的WPF ProgressBar

use*_*495 6 c# data-binding wpf progress-bar

我正在尝试在WPF中数据绑定ProgressBar的value属性.我有一个按钮设置为增加ProgressBar的值的数据绑定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>
Run Code Online (Sandbox Code Playgroud)

这是我的代码背后......

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

bic*_*bic 7

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);
}
Run Code Online (Sandbox Code Playgroud)


Hen*_*man 1

没有设置 Window(或 StackPanel)的 DataContext 的代码(已发布)。

要确定原因,请观察输出窗口中的绑定错误。


另外,

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

这会阻止消息处理,因此您的应用程序将“无响应”5 秒。不会进行任何输入处理和屏幕更新。在事件驱动的 GUI 中,繁忙循环根本就不好。

将此代码移至后台工作人员或使用计时器。