<Canvas x:Name="LayoutRoot" Background="white">
<Image Source="level1.jpg" Name="bg" Width="640" Height="480"
Canvas.Top="10" Canvas.Left="50"/>
<TextBlock Name="score">Scorehere</TextBlock>
</Canvas>void CompositionTarget_Rendering(object sender, EventArgs e)
{
if (DetectCollisionLeft(myCat, myZero))
{
LayoutRoot.Children.Remove(myZero);
}
}我基本上知道的是,当我的猫在游戏中与数字零发生冲突时,数字就消失了。如何让XAML中的TextBlock显示一个在每次收集数字时都会增加的数字。
谢谢
发布于 2011-04-30 10:23:31
因为我理解您的问题陈述,您希望在每次检测到冲突时更新分数。如果是这样,那么只需更新TextBlock.Text属性即可更新分数。
void CompositionTarget_Rendering(object sender, EventArgs e)
{
if (DetectCollisionLeft(myCat, myZero))
{
if(LayoutRoot.Children.Contains(myZero))
{
LayoutRoot.Children.Remove(myZero);
//Update the score as score = previousScore + 1
int scoreAsInt;
if(Int32.TryParse(score.Text, NumberStyles.Integer, CultureInfo.CurrentCulture, out scoreAsInt) != null)
{
scoreAsInt = scoreAsInt + 1;
score.Text = scoreAsInt.ToString(CultureInfo.CurrentCulture);
}
}
}
}请注意,您必须考虑分数对于整数范围来说太大的情况。在这种情况下,您可以重置分数或使用更大的类型,如long作为分数。
发布于 2011-04-30 10:39:21
我的第一个建议是,你需要将你的逻辑与视觉分开。这可以通过使用MVVM pattern来完成,也可以通过为score和cat编写数据模型类并将逻辑移动到那里来完成。对于这样一个简单的项目,MVVM可能有点过火,但当可视化数据和逻辑混合在一起时,可能很快就会出现不必要的问题和复杂性。
话虽如此,这里有一个简单的答案来解决你的问题。如果你想保留屏幕上的分数并更新它,根本没有理由删除它。只需更新文本值并将其移动到画布中的一个新的随机位置。如下所示:
if (DetectCollisionLeft(myCat, myZero))
{
Random rand = new Random();
score.Text = int.Parse(score.Text) + 1;
// Measure text for new random position
score.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
// Set the position of the text
Canvas.SetLeft(score, rand.Next(640 + 10 - score.DesiredSize.Width));
Canvas.SetTop(score, rand.Next(480 + 10 - score.DesiredSize.Height));
}可以有更好的方法来随机化分数的位置。例如,最好传入屏幕/父容器的宽度,而不是使用硬编码值640和480。希望这能将您引向正确的方向。
https://stackoverflow.com/questions/5838881
复制相似问题