加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:17:20 所属栏目:百科 来源:网络整理
导读:我正在尝试在 WPF中数据绑定ProgressBar的value属性.我有一个按钮设置为增加ProgressBar的值的数据绑定int属性.当我按下按钮时,它应该使ProgressBar的值从1增加到100.但是……它似乎没有工作,我不确定我做错了什么.这是我的XAML …… Window x:Class="Progre
我正在尝试在 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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读