我有以下示例代码,每次按下按钮时缩放:
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>
Run Code Online (Sandbox Code Playgroud)
*的.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));
}
}
Run Code Online (Sandbox Code Playgroud)
输出是:
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
Run Code Online (Sandbox Code Playgroud)
正如你所看到的那样,有一个问题,我认为通过使用Application.DoEvents();但是......它在.NET 4 中不存在先验.
该怎么办?
Fre*_*lad 129
尝试这样的事情
public static void DoEvents()
{
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background,
new Action(delegate { }));
}
Run Code Online (Sandbox Code Playgroud)
flq*_*flq 55
好吧,我刚刚开始研究一个在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;
}
Run Code Online (Sandbox Code Playgroud)
Dil*_*e-O 25
在WPF中不推荐使用旧的Application.DoEvents()方法,而是使用Dispatcher或后台工作线程来执行您所描述的处理.有关如何使用这两个对象的文章,请参阅链接.
如果您绝对必须使用Application.DoEvents(),那么您只需将system.windows.forms.dll导入您的应用程序并调用该方法即可.但是,这不建议使用,因为您正在失去WPF提供的所有优势.
小智 10
如果您只需要更新窗口图形,最好像这样使用
public static void DoEvents()
{
Application.Current.Dispatcher.Invoke(DispatcherPriority.Render,
new Action(delegate { }));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
83667 次 |
| 最近记录: |