我有以下示例代码,可以在每次按下按钮时进行缩放:
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中不存在先验。
该怎么办呢?
发布于 2010-12-22 01:25:19
旧的Application.DoEvents()方法在WPF中已被弃用,取而代之的是使用Dispatcher或Background Worker Thread来完成您所描述的处理。
如果一定要使用Application.DoEvents(),那么只需将system.windows.forms.dll导入应用程序并调用该方法即可。但是,我们并不推荐这样做,因为您正在失去WPF提供的所有优势。
发布于 2010-12-22 01:37:02
试试这样的东西
public static void DoEvents()
{
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background,
new Action(delegate { }));
}
发布于 2012-08-10 18:04:40
好吧,我刚刚遇到了一个例子,我开始处理一个在Dispatcher线程上运行的方法,它需要在不阻塞UI线程的情况下阻塞。事实证明,msdn解释了如何基于Dispatcher本身实现DoEvents():
public void DoEvents()
{
DispatcherFrame frame = new DispatcherFrame();
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
new DispatcherOperationCallback(ExitFrame), frame);
Dispatcher.PushFrame(frame);
}
public object ExitFrame(object f)
{
((DispatcherFrame)f).Continue = false;
return null;
}
(摘自Dispatcher.PushFrame Method)
有些人可能更喜欢用一种方法来执行相同的逻辑:
public static void DoEvents()
{
var frame = new DispatcherFrame();
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
new DispatcherOperationCallback(
delegate (object f)
{
((DispatcherFrame)f).Continue = false;
return null;
}),frame);
Dispatcher.PushFrame(frame);
}
https://stackoverflow.com/questions/4502037
复制相似问题