// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Linq;
using Avalonia.Data;
using Avalonia.LogicalTree;
using Avalonia.Styling;
namespace Avalonia.Controls
{
///
/// Adds common functionality to .
///
public static class ControlExtensions
{
///
/// Tries to bring the control into view.
///
/// The control.
public static void BringIntoView(this IControl control)
{
Contract.Requires(control != null);
control.BringIntoView(new Rect(control.Bounds.Size));
}
///
/// Tries to bring the control into view.
///
/// The control.
/// The area of the control to being into view.
public static void BringIntoView(this IControl control, Rect rect)
{
Contract.Requires(control != null);
var ev = new RequestBringIntoViewEventArgs
{
RoutedEvent = Control.RequestBringIntoViewEvent,
TargetObject = control,
TargetRect = rect,
};
control.RaiseEvent(ev);
}
///
/// Finds the named control in the scope of the specified control.
///
/// The type of the control to find.
/// The control to look in.
/// The name of the control to find.
/// The control or null if not found.
public static T FindControl(this IControl control, string name) where T : class, IControl
{
Contract.Requires(control != null);
Contract.Requires(name != null);
var nameScope = control.FindNameScope();
if (nameScope == null)
{
throw new InvalidOperationException("Could not find parent name scope.");
}
return nameScope.Find(name);
}
///
/// Adds or removes a pseudoclass depending on a boolean value.
///
/// The pseudoclasses collection.
/// The name of the pseudoclass to set.
/// True to add the pseudoclass or false to remove.
public static void Set(this IPseudoClasses classes, string name, bool value)
{
Contract.Requires(classes != null);
if (value)
{
classes.Add(name);
}
else
{
classes.Remove(name);
}
}
///
/// Sets a pseudoclass depending on an observable trigger.
///
/// The pseudoclasses collection.
/// The name of the pseudoclass to set.
/// The trigger: true adds the pseudoclass, false removes.
/// A disposable used to cancel the subscription.
public static IDisposable Set(this IPseudoClasses classes, string name, IObservable trigger)
{
Contract.Requires(classes != null);
return trigger.Subscribe(x => classes.Set(name, x));
}
}
}