using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
namespace Tango.SharedUI.Components
{
///
/// Represents an MVVM TextBox controller
///
///
public class TextController : DependencyObject
{
private TextBox _textBox;
private bool _isMouseDown;
///
/// Determines whether an element is Controller.
///
public static readonly DependencyProperty ControllerProperty =
DependencyProperty.RegisterAttached("Controller",
typeof(TextController), typeof(TextController),
new FrameworkPropertyMetadata(null,ControllerChanged));
///
/// On controller changed.
///
/// The d.
/// The instance containing the event data.
/// The text controller component can only handle elements of type TextBox.
private static void ControllerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d != null && e.NewValue != null)
{
if (!(d is TextBox))
{
throw new ArgumentException("The text controller component can only handle elements of type TextBox.");
}
(e.NewValue as TextController).SetTextBox(d as TextBox);
}
}
///
/// Sets the Controller attached property.
///
/// The element.
/// if set to true [value].
public static void SetController(FrameworkElement element, TextController value)
{
element.SetValue(ControllerProperty, value);
}
///
/// Gets the Controller attached property.
///
/// The element.
///
public static TextController GetController(FrameworkElement element)
{
return (TextController)element.GetValue(ControllerProperty);
}
///
/// Gets or sets a value indicating whether to automatically scroll to end of text.
///
public bool AutoScrollToEnd { get; set; }
///
/// Initializes a new instance of the class.
///
public TextController()
{
AutoScrollToEnd = true;
}
///
/// Sets the text box.
///
/// The text box.
private void SetTextBox(TextBox textBox)
{
_textBox = textBox;
_textBox.PreviewMouseDown += (_, __) => _isMouseDown = true;
_textBox.PreviewMouseUp += (_, __) => _isMouseDown = false;
}
///
/// Appends the specified text.
///
/// The text.
public void WriteLine(String text)
{
Write(text + Environment.NewLine);
}
///
/// Appends the specified text.
///
/// The text.
public void Write(String text)
{
Invoke(() =>
{
_textBox.AppendText(text);
if (AutoScrollToEnd && !_isMouseDown)
{
ScrollToEnd();
}
});
}
///
/// Sets the specified text.
///
/// The text.
public void Set(String text)
{
Invoke(() =>
{
_textBox.Text = text;
if (AutoScrollToEnd && !_isMouseDown)
{
ScrollToEnd();
}
});
}
///
/// Clears the text.
///
public void Clear()
{
Invoke(() =>
{
_textBox.Clear();
});
}
///
/// Scrolls to the end of the text.
///
public void ScrollToEnd()
{
_textBox.ScrollToEnd();
}
///
/// Invokes the specified action.
///
/// The action.
private void Invoke(Action action)
{
Dispatcher.BeginInvoke(action);
}
}
}