哪里Application.DoEvents()在WPF?Application、DoEvents、WPF

2023-09-02 21:08:09 作者:挽梦亦清歌

我有下面的示例code表示变焦每次按钮pressed:

I have the following sample code that zooms each time a button is pressed:

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

*.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。

as you can see, there is a problem, that I thought solve by using Application.DoEvents(); but... it does not exist a priori in .NET 4.

怎么办?

推荐答案

旧Application.DoEvents()方法是去$ P $:// MSDN。 microsoft.com/en-us/magazine/cc163328.aspx">Dispatcher 或Background工作线程的为你描述做处理。请参阅有关如何使用这两种对象几篇文章的链接。

The old Application.DoEvents() method has been deprecated in WPF in favor of using a Dispatcher or a Background Worker Thread to do the processing as you have described. See the links for a couple of articles on how to use both objects.

如果你绝对必须使用Application.DoEvents(),那么你可以简单地导入System.Windows.Forms.dll程序到应用程序并调用该方法。但是,这真的是不推荐的,因为你失去所有的WPF提供了优势。

If you absolutely must use Application.DoEvents(), then you could simply import the system.windows.forms.dll into your application and call the method. However, this really isn't recommended, since you're losing all the advantages that WPF provides.