标题:WPF画布如何实时刷新
只看楼主
南川
Rank: 4
等 级:业余侠客
威 望:1
帖 子:111
专家分:235
注 册:2010-6-25
结帖率:86.21%
已结贴  问题点数:10 回复次数:1 
WPF画布如何实时刷新
我用WPF写了一个简单的程序,就是在主窗体上放了一个Canvas和一个Button。当单击Button的时候,在Canvas上重复一个动作10次:就是每1秒画一个圆,放上。但我发现动作画完以前Canvas一直处于空白,直到10秒画完了才显示出来图像出来。想实现的效果是每1秒钟画布都更新一下图片。代码如下:

MainWindow.xaml
程序代码:
<Window x:Class="CanvasTest.MainWindow"
        xmlns="http://schemas."
        xmlns:x="http://schemas."
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Canvas Height="232" HorizontalAlignment="Left" Margin="12,12,0,0" Name="canvas1" VerticalAlignment="Top" Width="467"></Canvas>
        <Button Content="Button" Height="23" Name="button1" Width="75" Click="button1_Click" Margin="12,265,416,23" />
    </Grid>
</Window>




MainWindow.xaml.cs
程序代码:
public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < 10; i++)
            {
                if (i % 2 == 0)
                {
                    Ellipse el = new Ellipse();
                    el.Height = 30;
                    el.Width = 60;
                    el.Fill = Brushes.Red;
                    el.Stroke = Brushes.Black;
                    canvas1.Children.Add(el);
                }

                else
                {

                    Ellipse el = new Ellipse();
                    el.Height = 30;
                    el.Width = 60;
                    el.Fill = Brushes.Yellow;
                    el.Stroke = Brushes.Green;
                    canvas1.Children.Add(el);
                }

                System.Threading.Thread.Sleep(1000);
            }
        }


CanvasTest.rar (39.53 KB)
搜索更多相关主题的帖子: 如何 
2011-10-30 12:28
serious
Rank: 6Rank: 6
等 级:侠之大者
威 望:1
帖 子:81
专家分:497
注 册:2009-8-18
得分:10 
为了做你想,需要用另的线程:
程序代码:
private void button1_Click(object sender, RoutedEventArgs e)
{
    Thread anotherThread = new Thread(() =>
        {
            for (int i = 0; i < 10; i++)
            {
                canvas1.Dispatcher.BeginInvoke((Action)(() =>
                    {
                        canvas1.Children.Add(new Ellipse
                        {
                            Height = 30,
                            Width = 60,
                            Fill = i % 2 == 0 ? Brushes.Red : Brushes.Yellow,
                            Stroke = i % 2 == 0 ? Brushes.Black : Brushes.Green
                        });
                    }));

                Thread.Sleep(1000);
            }
        });

    anotherThread.SetApartmentState(ApartmentState.STA);
    anotherThread.Start();
}

2011-10-30 22:54



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-353826-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.053339 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved