一尘不染

WPF中的Application.DoEvents()在哪里?

c#

我有以下示例代码,每次按下按钮时都会缩放:

XAML:

<Window x:Class="WpfApplication12.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">

    <Canvas x:Name="myCanvas">

        <Canvas.LayoutTransform>
            <ScaleTransform x:Name="myScaleTransform" />
        </Canvas.LayoutTransform>

        <Button Content="Button" 
                Name="myButton" 
                Canvas.Left="50" 
                Canvas.Top="50" 
                Click="myButton_Click" />
    </Canvas>
</Window>
  • .cs

    public partial class MainWindow : Window
    {
    public MainWindow()
    {
    InitializeComponent();
    }

    private void myButton_Click(object sender, RoutedEventArgs e)
    {
        Console.WriteLine("scale {0}, location: {1}", 
            myScaleTransform.ScaleX,
            myCanvas.PointToScreen(GetMyByttonLocation()));
    
        myScaleTransform.ScaleX =
            myScaleTransform.ScaleY =
            myScaleTransform.ScaleX + 1;
    
        Console.WriteLine("scale {0}, location: {1}",
            myScaleTransform.ScaleX,
            myCanvas.PointToScreen(GetMyByttonLocation()));
    }
    
    private Point GetMyByttonLocation()
    {
        return new Point(
            Canvas.GetLeft(myButton),
            Canvas.GetTop(myButton));
    }
    

    }

输出为:

scale 1, location: 296;315
scale 2, location: 296;315

scale 2, location: 346;365
scale 3, location: 346;365

scale 3, location: 396;415
scale 4, location: 396;415

如您所见,存在一个问题,我认为可以通过使用来解决,Application.DoEvents();但是.... NET 4 中不存在 先验 问题。

该怎么办?


阅读 698

收藏
2020-05-19

共1个答案

一尘不染

WPF中不推荐使用旧的Application.DoEvents()方法,而是使用分派器后台工作线程执行您所描述的处理。有关如何使用这两个对象的文章,请参见链接。

如果绝对必须使用Application.DoEvents(),则只需将system.windows.forms.dll导入应用程序并调用该方法。但是,实际上不建议这样做,因为您将失去WPF提供的所有优势。

2020-05-19