2011-12-09 71 views
0

我在我的页面上有一个TextBlockTextnull(“”)。当我点击一个按钮时,我想为此TextBlock更改文本值,请暂停半秒,然后将TextBlock一个像素一次移动到某个点。更新Thread.Sleep之前的页面布局()

我试着用Thread.Sleep(),但到目前为止,我有一个问题。我点击按钮,UI线程暂停半秒钟,然后TextBlock突然出现并开始移动。我希望它在我点击按钮后立即出现。

P.S:我知道了Thread.Sleep()不工作。我愿意使用任何有效的东西。

回答

4

故事板和动画是用于在屏幕上移动的物品的优选机制。首先,它们被优化为与电话线程模型一起工作。另一种情况是,当你制作一个无响应的应用程序时,将你的UI线程置于睡眠状态是一个坏主意。

下面是如何移动texblock用故事板一个简单的例子。

的UI元素。

<Grid 
    x:Name="ContentPanel" 
    Grid.Row="1" 
    Margin="12,0,12,0"> 
    <TextBlock 
    Margin='79,263,177,307' 
    Name='textBlock1' 
    Text='TextBlock' 
    RenderTransformOrigin="0.5,0.5"> 
    <TextBlock.RenderTransform> 
     <CompositeTransform /> 
    </TextBlock.RenderTransform> 
    </TextBlock> 
    <Button 
    Content="Button" 
    Height="80" 
    Margin="116,0,188,144" 
    VerticalAlignment="Bottom" 
    Click='Button_Click' /> 
</Grid> 

,故事情节,在页面的资源部分定义。

<phone:PhoneApplicationPage.Resources> 
<Storyboard 
    x:Name="MoveTextBlockStoryboard"> 
    <DoubleAnimationUsingKeyFrames 
    Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateX)" 
    Storyboard.TargetName="textBlock1"> 
    <EasingDoubleKeyFrame 
     KeyTime="0" 
     Value="0" /> 
    <EasingDoubleKeyFrame 
     KeyTime="0:0:1.1" 
     Value="120" /> 
    </DoubleAnimationUsingKeyFrames> 
    <DoubleAnimationUsingKeyFrames 
    Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateY)" 
    Storyboard.TargetName="textBlock1"> 
    <EasingDoubleKeyFrame 
     KeyTime="0" 
     Value="0" /> 
    <EasingDoubleKeyFrame 
     KeyTime="0:0:1.1" 
     Value="-105" /> 
    </DoubleAnimationUsingKeyFrames> 
</Storyboard> 

改变文本,并开始故事板的代码。

private void Button_Click(object sender, RoutedEventArgs e) { 
    textBlock1.Text = "new text"; 
    MoveTextBlockStoryboard.Begin(); 

} 
+0

+1,这是你如何做到的。手动在页面上移动元素(在UI线程上!)是一个坏主意。我会建议反对它。 – Joe

+0

它像一个魅力。谢谢!对于迟到的标记作为回应很抱歉。 –

3

尝试使用故事板而不是编写代码来执行此操作。我认为它比手动方法更适合你。

+0

或者考虑在BackgroundWorker线程中暂停,然后调用回UI线程来更新它。但克里斯的做法更好。 – invalidusername