using System;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
namespace Avalonia.Controls.Primitives
{
///
/// A text block that displays a character prefixed with an underscore as an access key.
///
public class AccessText : TextBlock
{
///
/// Defines the attached property.
///
public static readonly AttachedProperty ShowAccessKeyProperty =
AvaloniaProperty.RegisterAttached("ShowAccessKey", inherits: true);
///
/// The access key handler for the current window.
///
private IAccessKeyHandler _accessKeys;
///
/// Initializes static members of the class.
///
static AccessText()
{
AffectsRender(ShowAccessKeyProperty);
}
///
/// Initializes a new instance of the class.
///
public AccessText()
{
this.GetObservable(TextProperty).Subscribe(TextChanged);
}
///
/// Gets the access key.
///
public char AccessKey
{
get;
private set;
}
///
/// Gets or sets a value indicating whether the access key should be underlined.
///
public bool ShowAccessKey
{
get { return GetValue(ShowAccessKeyProperty); }
set { SetValue(ShowAccessKeyProperty, value); }
}
///
/// Renders the to a drawing context.
///
/// The drawing context.
public override void Render(DrawingContext context)
{
base.Render(context);
int underscore = Text?.IndexOf('_') ?? -1;
if (underscore != -1 && ShowAccessKey)
{
var rect = TextLayout.HitTestTextPosition(underscore);
var offset = new Vector(0, -1.5);
context.DrawLine(
new Pen(Foreground, 1),
rect.BottomLeft + offset,
rect.BottomRight + offset);
}
}
///
protected override TextLayout CreateTextLayout(Size constraint, string text)
{
return base.CreateTextLayout(constraint, StripAccessKey(text));
}
///
protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnAttachedToVisualTree(e);
_accessKeys = (e.Root as IInputRoot)?.AccessKeyHandler;
if (_accessKeys != null && AccessKey != 0)
{
_accessKeys.Register(AccessKey, this);
}
}
///
protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnDetachedFromVisualTree(e);
if (_accessKeys != null && AccessKey != 0)
{
_accessKeys.Unregister(this);
_accessKeys = null;
}
}
///
/// Returns a string with the first underscore stripped.
///
/// The text.
/// The text with the first underscore stripped.
private string StripAccessKey(string text)
{
var position = text.IndexOf('_');
if (position == -1)
{
return text;
}
else
{
return text.Substring(0, position) + text.Substring(position + 1);
}
}
///
/// Called when the property changes.
///
/// The new text.
private void TextChanged(string text)
{
var key = (char)0;
if (text != null)
{
int underscore = text.IndexOf('_');
if (underscore != -1 && underscore < text.Length - 1)
{
key = text[underscore + 1];
}
}
AccessKey = key;
if (_accessKeys != null && AccessKey != 0)
{
_accessKeys.Register(AccessKey, this);
}
}
}
}