如何通过代码(WPF)绘制自定义进度条

时间:2015-11-25 04:15:02

标签: c# wpf custom-controls onrender

我创建了一个WinForms自定义进度条,但它有点闪烁。它是双缓冲的,但它仍然有点闪烁,所以我尝试使用WPF来查看是否有小闪烁可以消失。

我对WPF来说是全新的。据我所知,WPF的OnPaint(PaintEventArgs e)方法称为OnRender(DrawingContext drawingContext)。

System.Drawing.Image BMP = System.Drawing.Image.FromFile(MyImagePath);
BMP = new Bitmap(BMP, (int)Width, (int)Height);

// Working method I founded in this site for converting a System.Drawing.Bitmap to a BitmapSource
ImageSource Rainbow = CreateBitmapSourceFromGdiBitmap((Bitmap)BMP);

// Working method I founded in this site for converting a System.Drawing.Bitmap to System.Windows.Media.Brush
System.Windows.Media.Brush RainbowBrush = CreateBrushFromBitmap((Bitmap)BMP);

protected override void OnRender(DrawingContext DrawingContext)
{
    if (Value > 0)
    {
        Rect myRect = new Rect(0, 0, ((Width * Value) / (Maximum - Minimum)) + 5, Height);
        DrawingContext.DrawRectangle(RainbowBrush, new System.Windows.Media.Pen(), myRect);
    }
}

问题:

enter image description here

我的形象不是"覆盖"绿色的酒吧。 现在,如果我将Rect myRect = new Rect(0, 0, ((Width * Value) / (Maximum - Minimum)) + 5, Height);改为......让我们说Rect myRect = new Rect(0, 50, ((Width * Value) / (Maximum - Minimum)) + 5, Height);,结果如下:

enter image description here

因此,彩虹条被绘制,但不在进度条上。如果我写Rect myRect = new Rect(0, 0, ((Width * Value) / (Maximum - Minimum)) + 5, Height);,它会被绘制但在进度条下方。如何获得彩虹进度条(以及其他自定义进度条)?

感谢您的帮助。

编辑:原来的进度条(那个闪烁一点)远远超过了彩虹。我刚开始使用彩虹在WPF中进行快速测试,然后尝试添加其他内容。万一你想知道为什么这么简单的进度条在WinForms中闪烁。这是因为WinForms比彩虹更多。谢谢。

1 个答案:

答案 0 :(得分:0)

如果您需要在ProgressBar Window应用的WPF开头创建<Window x:Class="PasswordBoxMVVM.MainWindow" <!--The code omitted for the brevity--> Title="MainWindow" Height="350" Width="525"> <StackPanel x:Name="stackPanel"> <TextBox x:Name="textBox" <DataGrid /> </StackPanel> </Window> ,则可以使用以下代码:

你的xaml:

public MainWindow()
{
   InitializeComponent();    
   PaintProgressBar();
}

private void PaintProgressBar()
{            
   ProgressBar progressBar = new ProgressBar();
   progressBar.IsIndeterminate = true;
   progressBar.Margin = new Thickness(10, 0, 10, 10);
   progressBar.Visibility = Visibility.Visible;
   progressBar.Height = 25;
   //progressBar.FlowDirection = FlowDirection.LeftToRight;
   progressBar.Foreground = System.Windows.Media.Brushes.Green;
   progressBar.Background = System.Windows.Media.Brushes.Red;
   progressBar.Value = 50;
   stackPanel.Children.Add(progressBar);
}

<强>代码隐藏:

progressBar.Foreground

属性ProgressBar设置<null>的颜色。

相关问题