2013-04-10 98 views
0

我在窗体上有一个按钮。按下按钮矩形必须移动。但没有任何反应,为什么? 对我来说重要的是该按钮是异步的,因为我想调用未来的异步方法。不移动矩形

XAML:

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}"> 
    <Button Content="Start" HorizontalAlignment="Left" Margin="849,152,0,0" VerticalAlignment="Top" Height="45" Width="196" Click="Button_Click_1"/> 
    <Rectangle x:Name="rect" Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="100" Stroke="Black" VerticalAlignment="Top" Width="100"/> 

</Grid> 

C#:

private double step = 5; 

private async void Button_Click_1(object sender, RoutedEventArgs e) 
    { 
     while (true) 
     { 
      MoveRect(); 
      Sleep(100); 
     } 
    } 

private void MoveRect() 
    { 
     rect.Margin = new Thickness(rect.Margin.Left + step, rect.Margin.Top + step, rect.Margin.Right - step, rect.Margin.Bottom - step); 
    } 

static void Sleep(int ms) 
    { 
     new System.Threading.ManualResetEvent(false).WaitOne(ms); 
    } 
+0

这是什么技术? wpf/silverlight? – 2013-04-10 11:13:07

+1

你想实现什么?你为什么不使用动画? – Xyroid 2013-04-10 11:19:36

回答

1

如果您正在开发Windows应用商店应用,那么您的按钮点击事件将是这样的。

using Windows.UI.Core; 

private async void Button_Click_1(object sender, RoutedEventArgs e) 
{ 
    while (true) 
    { 
     await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,() => MoveRect()); 
     Sleep(100); 
    } 
} 
0

好吧,这段代码引发了不少问题。最重要的是@ Xyroid的一个:你为什么不使用动画? WPF/Silverlight已经内置了支持这样的事情。

Hovewer,考虑到你完全确定你在做什么,只是想您所提交的工作,我可以提出以下速战速决代码:

while (true) 
{ 
    Dispatcher.Invoke(new Action(MoveRect)); 
    Sleep(100); 
} 

它工作在我的电脑(R)。但让我知道它是否对你有帮助。