c# – 带有值数据绑定的WPF ProgressBar

前端之家收集整理的这篇文章主要介绍了c# – 带有值数据绑定的WPF ProgressBar前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试在 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,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线程.用Wait(50)替换你的Thread.Sleep(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);
}
原文链接:https://www.f2er.com/csharp/243033.html

猜你在找的C#相关文章