ConditionalRender.razor.cs
using System;
using System.Linq;
using Sandbox.Diagnostics;
namespace BetterUI;
/// <summary>
/// A panel that will only render if a condition is true. The condition is a
/// function that is called every frame to check if the panel should be
/// rendered.
/// </summary>
public partial class ConditionalRender : Panel
{
private bool _previousCondition;
/// <summary>
/// The condition function that determines if the panel should be rendered.
/// </summary>
public Func<bool> Condition { get; set; } = null!;
protected override void OnAfterTreeRender( bool firstTime )
{
Assert.NotNull( Condition, "ConditionalRender must have a condition function" );
}
public override void Tick()
{
var condition = Condition();
if ( _previousCondition == condition ) return;
_previousCondition = condition;
for ( var i = 0; i < Children.Count(); i++ )
{
var child = Children.ElementAt(i);
if ( !child.IsValid() ) continue;
child.BindClass("hidden", () => !condition);
}
}
protected override int BuildHash() => HashCode.Combine( Condition.Invoke() );
}