[WPF] Behavior를 사용해 TextBox.ScrollToEnd() 실행

JEONGKI'S Note·2023년 2월 27일
0

Behavior를 이용해 TextBox 내용변경을 수신하고
새 텍스트가 추가되면 자동으로 끝까지 스크롤합니다.

CS File

An attached behavior is a way to extend the functionality of a control without subclassing it. You can create an attached behavior that listens to changes in the text box content and automatically scrolls to the end when new text is added. Here's an example:

public static class TextBoxBehavior
{
    public static readonly DependencyProperty AutoScrollToEndProperty =
        DependencyProperty.RegisterAttached("AutoScrollToEnd", typeof(bool),
        typeof(TextBoxBehavior), new FrameworkPropertyMetadata(false, OnAutoScrollToEndChanged));

    public static bool GetAutoScrollToEnd(DependencyObject obj)
    {
        return (bool)obj.GetValue(AutoScrollToEndProperty);
    }

    public static void SetAutoScrollToEnd(DependencyObject obj, bool value)
    {
        obj.SetValue(AutoScrollToEndProperty, value);
    }

    private static void OnAutoScrollToEndChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var textBox = d as TextBox;
        if (textBox == null)
            return;

        var newValue = (bool)e.NewValue;
        if (newValue)
        {
            textBox.TextChanged += TextBox_TextChanged;
        }
        else
        {
            textBox.TextChanged -= TextBox_TextChanged;
        }
    }

    private static void TextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        var textBox = sender as TextBox;
        if (textBox == null)
            return;

        textBox.ScrollToEnd();
    }
}

In the example above, the TextBoxBehavior class defines an attached property called AutoScrollToEnd. When this property is set to true on a text box control, the behavior attaches an event handler to the TextChanged event of the text box. The event handler then calls ScrollToEnd() on the text box control when new text is added.

To use the attached behavior, you can set the TextBoxBehavior.AutoScrollToEnd attached property to true on your text box control:

적용하고자 하는 TextBox에 적용합니다.

Xaml File

<Page xmlns:behaviors="clr-namespace:Project.Behaviors"/>

<TextBox Text="{Binding TextBoxContent, UpdateSourceTrigger=PropertyChanged}"
         VerticalScrollBarVisibility="Auto"
         behaviors:TextBoxBehavior.AutoScrollToEnd="True" />
profile
주니어 개발자 공부노트입니다 :)

0개의 댓글