【问题标题】:Moveble label on timer计时器上的可移动标签
【发布时间】:2021-12-24 07:27:12
【问题描述】:

我使用 Xamarin.Forms,我想在我的应用程序上实时(按计时器)创建可移动标签。我创建了这个逻辑:

XAML 代码:

<ScrollView Grid.Row="0" VerticalOptions="End" 
                         Orientation="Horizontal" 
                         HorizontalScrollBarVisibility="Never"
                         Margin="0, 0, 0, 40"
                        x:Name="TickerTitleSound"
                        IsEnabled="False" 
                        >
                <Label
                Text="{Binding SpecialText}" />
            </ScrollView>

以及后面的 C# 代码:

// Direction - bool class member
TickerTitleSound.Scrolled += (sender, e) =>
{
    double scrollingSpace = TickerTitleSound.ContentSize.Width - TickerTitleSound.Width;
    if(TickerTitleSound.ScrollX >= scrollingSpace)
    {
        Direction = false;
    }
    else if(TickerTitleSound.ScrollX <= 0)
    {
        Direction = true;
    }
};
Timer timerSound = new Timer() { Interval = 100 };
timerSound.Elapsed += async (o, e) =>
{
     await Task.Run(() =>
     {
         Device.BeginInvokeOnMainThread(() =>
         {
             if (Direction)
             {
                 TickerTitleSound.ScrollToAsync(TickerTitleSound.ScaleX + 10, 0, false);
             }
             else
             {
                 TickerTitleSound.ScrollToAsync(TickerTitleSound.ScaleX - 10, 0, false);
             }
          });
      });
};
timerSound.Start();

但是这段代码不起作用。我想得到这个结果:

这是怎么做的?我有

【问题讨论】:

  • 你为什么用ScaleX而不是ScrollX

标签: c# xamarin xamarin.forms


【解决方案1】:

你可以设置标签的TranslationX,下面是我的示例代码:

public partial class TestPage1 : ContentPage
{
    private bool Execute { get; set; }
    public TestPage ()
    {
        InitializeComponent ();
        Label1.Text = "This is to simulate a really long sentence for testing purposes";
        Label1.HorizontalOptions = LayoutOptions.Start;
        Label1.VerticalTextAlignment = TextAlignment.Center;
        Label1.LineBreakMode = LineBreakMode.NoWrap;
    }
    protected override void OnAppearing()
    {
        base.OnAppearing();
        Execute = true;

        Device.StartTimer(TimeSpan.FromMilliseconds(50), () =>
        {
            Label1.TranslationX -= 5f;

            if (Math.Abs(Label1.TranslationX) > Width)
            {
                Label1.TranslationX = Label1.Width;
            }

            return Execute;
        });
    }
    protected override void OnDisappearing()
    {
        base.OnDisappearing();

        Execute = false;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多