【问题标题】:Xamarin.Forms - How do I make a click counter?Xamarin.Forms - 如何制作点击计数器?
【发布时间】:2019-10-27 02:42:24
【问题描述】:

我正在使用 Xamarin.Forms 进行 Android 应用程序开发,并且希望在玩家点击屏幕时创建一个计数器。如何制作一个计数器来计算屏幕上的点击次数?如果有帮助,我正在使用 Visual Studio 2019。谢谢!

这是我的 xaml.cs 代码(不要介意 InitializeComponent 和花括号的数量。这些都很好): enter image description here

这是我的 .xaml 代码: enter image description here

【问题讨论】:

标签: c# android xamarin xamarin.forms


【解决方案1】:

你能做到吗

在 XAML 中

<StackLayout Spacing="15">
    <!-- Place new controls here -->
    <Label Text="0" x:Name="lblCount" 
       HorizontalOptions="Center"
       VerticalOptions="CenterAndExpand" />

    <Button Text="Increment" Clicked="Increment"/>
</StackLayout>

在 XAML.cs 中

public partial class MainPage : ContentPage
{
    int lblValue = 0;
    public MainPage()
    {
        InitializeComponent();
    }
    private void Increment(object sender, EventArgs e)
    {
        lblValue++;
        lblCount.Text = lblValue.ToString();
    }
}

这是解决这个问题的简单方法,如果您需要使用绑定或其他功能告诉我。

就像杰森说的,我建议你看看文档

【讨论】:

  • 代码无法识别 .cs 文件中的 lblCount。从你说的和我在网上看到的猜测,这是一个有约束力的问题。我该如何解决这个问题?我查看了文档,但我无法完全掌握这个特定问题的概念。
  • 嗨,lblCount 是
  • 很抱歉,但我仍然不确定如何解决此问题。我正在使用不同的可能解决方案,它总是说 .cs 文件中的 lblCount“在当前上下文中不存在”。
  • 这里放一张xaml代码和xaml.cs代码(标签的代码)的截图,或者把代码贴在这里,也许我可以帮助你。
  • 好的,我用代码文件的截图更新了我的帖子。
【解决方案2】:

您可以在主框架中添加手势识别器(例如 stacklayout)

XAML

<StackLayout BackgroundColor="#313FA0">
    <StackLayout.GestureRecognizers>
        <TapGestureRecognizer Tapped="OnTapped"/>
    </StackLayout.GestureRecognizers>

 //All page stuff


</StackLayout>

C#

public partial class MainPage : ContentPage
{

    public MainPage()
    {
        InitializeComponent();
    }

   int taps = 0;
    private void OnTapped(object sender, EventArgs e)
    {
        taps++;
        Console.Writeline(taps.ToString());
    }
}

【讨论】:

    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多