来自WPF开发,我在玩ASP。NET,Blazor和我在理解以下内容时遇到了一些困难:例如,我想将CSS类的值绑定到代码隐藏类的属性。
@inherits TextGenerator
<style>
.mycssclass
{
opacity: @TextOpacity;
transition: opacity 2s;
}
</style>
<div class="modal-dialog-centered">
<h1>@Text</h1>
</div>
这就是类背后的代码:
public class TextGenerator : ComponentBase
{
public event Func<Task> OnPropertyChanged;
private string _text;
public string Text
{
get
{
return _text;
}
set
{
_text = value;
OnPropertyChanged.Invoke();
}
}
private float _textOpacity;
public float TextOpacity
{
get
{
return _textOpacity;
}
set
{
_textOpacity = value;
OnPropertyChanged.Invoke();
}
}
protected async Task StartTextSlideShow()
{
Text = "";
TextOpacity = 1.0f;
for (int i = 0; i < 1000; i++)
{
Text = "Test #" + i.ToString();
await Task.Delay(100);
}
}
protected override void OnInitialized()
{
OnPropertyChanged += PropertyChange;
_ = StartTextSlideShow();
}
public async Task PropertyChange()
{
await InvokeAsync(() =>
{
StateHasChanged();
});
}
}
我的问题如下:如何设置不透明度的初始值或回退值?例如,在这种情况下,我希望将不透明度初始化为0
,这样当我在StartTextSlideShow()
中将其设置为1.0f
时,文本将淡入
这里有一个类似的答案,它会在幻灯片中出现,并为每个伪图片淡出。
剃刀代码:
@page "/Text"
<style>
.mycssclass
{
opacity: @_opacity;
transition: opacity @_transition;
}
</style>
<div class="modal-dialog-centered mycssclass @_cssClass p-5">
<h1 class="">@_text</h1>
</div>
以及背后的代码:
using Microsoft.AspNetCore.Components;
using System.Timers;
namespace StackOverflow.Server.Pages
{
public partial class TextGenerator : ComponentBase
{
System.Timers.Timer _timer = new System.Timers.Timer();
private string _text = "Slide Show Starting";
private decimal _opacity = 0m;
private string _transition = "0s";
private int _counter = 0;
private int _pictureCount = 5;
private string _cssClass = "bg-white text-white-500 border border-secondary";
protected override void OnInitialized()
{
_opacity = 1m;
_transition = "2s";
_timer.Interval = 4000;
_timer.AutoReset = true;
_timer.Elapsed += TimerElapsed;
_timer.Start();
}
public async void TimerElapsed(Object? sender, System.Timers.ElapsedEventArgs e)
{
_cssClass = "bg-primary text-white";
_counter++;
_opacity = 0m;
_transition = "0s";
await this.InvokeAsync(StateHasChanged);
await Task.Delay(1);
_text = $"Picture {_counter}";
_opacity = 1m;
_transition = "2s";
await this.InvokeAsync(StateHasChanged);
if (_counter >= _pictureCount)
_timer.Stop();
}
}
}